Skip to content

Commit 90ad3fd

Browse files
committed
apply code review suggestions
1 parent 38dcbdf commit 90ad3fd

File tree

7 files changed

+76
-65
lines changed

7 files changed

+76
-65
lines changed
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
> [!CAUTION]
2-
> **It's recommended to keep the total size of custom claims in the session token under 1.2KB.** Exceeding this size can have adverse effects, such as possible infinite redirect loops in Next.js applications. It's recommended to move particularly large claims out of the JWT and fetch these using a separate API call from your backend. [Learn more](/docs/backend-requests/resources/session-tokens#size-limitations).
2+
> Clerk stores the session token in a cookie, and most browsers cap cookie size at [**4KB**](https://datatracker.ietf.org/doc/html/rfc2109#section-6.3). After accounting for the size of Clerk's default claims, the cookie can support **up to 1.2KB** of custom claims. Exceeding this limit will cause the cookie to not be set, which will break your app as Clerk depends on cookies to work properly. [Learn more](/docs/backend-requests/resources/session-tokens#size-limitations).

docs/backend-requests/custom-session-token.mdx

Lines changed: 39 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,15 @@ This guide will show you how to customize a session token to include additional
1717
1. In the Clerk Dashboard, navigate to the [**Sessions**](https://dashboard.clerk.com/last-active?path=sessions) page.
1818
1. Under **Customize session token**, in the **Claims** editor, you can add any claim to your session token that you need and select **Save**.
1919

20-
The following example adds the `metadata` claim to the session token.
20+
The following example adds the `fullName` and `primaryEmail` claims to the session token.
2121

2222
![Clerk Dashboard showing the custom claim modal](/docs/images/custom-session-token/example.png)
2323

2424
## Use the custom claims in your application
2525

2626
The [`Auth`](/docs/references/backend/types/auth-object) object includes a `sessionClaims` property that contains the custom claims you added to your session token. Accessing the `Auth` object differs depending on the framework you are using. See the [reference doc](/docs/references/backend/types/auth-object) for more information.
2727

28-
The following example demonstrates how to access the `metadata` claim that was added to the session token in the last step.
28+
The following example demonstrates how to access the `fullName` and `primaryEmail` claims that were added to the session token in the last step.
2929

3030
<Tabs items={["Next.js", "Astro", "Express", "Go", "React Router", "Remix", "Tanstack React Start"]}>
3131
<Tab>
@@ -41,9 +41,11 @@ This guide will show you how to customize a session token to include additional
4141
export async function GET() {
4242
const { sessionClaims } = await auth()
4343

44-
const metadata = sessionClaims?.metadata
44+
const fullName = sessionClaims?.fullName
4545

46-
return NextResponse.json({ metadata })
46+
const primaryEmail = sessionClaims?.primaryEmail
47+
48+
return NextResponse.json({ fullName, primaryEmail })
4749
}
4850
```
4951

@@ -55,9 +57,11 @@ This guide will show you how to customize a session token to include additional
5557
// Use `getAuth()` to get the user's ID and session claims
5658
const { sessionClaims } = getAuth(req)
5759

58-
const metadata = sessionClaims.metadata
60+
const fullName = sessionClaims?.fullName
61+
62+
const primaryEmail = sessionClaims?.primaryEmail
5963

60-
return res.status(200).json({ metadata })
64+
return res.status(200).json({ fullName, primaryEmail })
6165
}
6266
```
6367
</CodeBlockTabs>
@@ -78,9 +82,11 @@ This guide will show you how to customize a session token to include additional
7882
return new Response('Unauthorized', { status: 401 })
7983
}
8084

81-
const metadata = sessionClaims.metadata
85+
const fullName = sessionClaims?.fullName
8286

83-
return new Response(JSON.stringify({ metadata }))
87+
const primaryEmail = sessionClaims?.primaryEmail
88+
89+
return new Response(JSON.stringify({ fullName, primaryEmail }))
8490
}
8591
```
8692
</Tab>
@@ -102,9 +108,11 @@ This guide will show you how to customize a session token to include additional
102108
const getSessionClaims = (req, res, next) => {
103109
const { sessionClaims } = getAuth(req)
104110

105-
const metadata = sessionClaims.metadata
111+
const fullName = sessionClaims?.fullName
112+
113+
const primaryEmail = sessionClaims?.primaryEmail
106114

107-
return res.status(200).json({ metadata })
115+
return res.status(200).json({ fullName, primaryEmail })
108116
}
109117

110118
app.get('/profile', requireAuth(), getSessionClaims)
@@ -133,7 +141,8 @@ This guide will show you how to customize a session token to include additional
133141
)
134142

135143
type CustomSessionClaims struct {
136-
metadata string `json:"metadata"`
144+
FullName string `json:"fullName"`
145+
PrimaryEmail string `json:"primaryEmail"`
137146
}
138147

139148
func customClaimsConstructor(ctx context.Context) any {
@@ -172,7 +181,7 @@ This guide will show you how to customize a session token to include additional
172181
if !ok {
173182
// Handle the error how you see fit
174183
} else {
175-
fmt.Fprintf(w, `{"public_metadata": "%s"}`, customClaims.metadata)
184+
fmt.Fprintf(w, `{"full_name": "%s", "primary_email": "%s"}`, customClaims.FullName, customClaims.PrimaryEmail)
176185
}
177186
}
178187
```
@@ -196,19 +205,21 @@ This guide will show you how to customize a session token to include additional
196205
return redirect('/sign-in?redirect_url=' + args.request.url)
197206
}
198207

199-
const metadata = sessionClaims.metadata
208+
const fullName = sessionClaims.fullName
209+
210+
const primaryEmail = sessionClaims.primaryEmail
200211

201212
return {
202-
metadata,
213+
fullName: JSON.stringify(fullName),
214+
primaryEmail: JSON.stringify(primaryEmail),
203215
}
204216
}
205217

206218
export default function Profile({ loaderData }: Route.ComponentProps) {
207219
return (
208220
<div>
209-
<p>
210-
Welcome {userId}, your public metadata is {loaderData.metadata}
211-
</p>
221+
<p>Welcome {loaderData.fullName}</p>
222+
<p>Your email is {loaderData.primaryEmail}</p>
212223
</div>
213224
)
214225
}
@@ -232,9 +243,11 @@ This guide will show you how to customize a session token to include additional
232243
return redirect('/sign-in?redirect_url=' + args.request.url)
233244
}
234245

235-
const metadata = sessionClaims.metadata
246+
const fullName = sessionClaims.fullName
247+
248+
const primaryEmail = sessionClaims.primaryEmail
236249

237-
return { metadata }
250+
return { fullName, primaryEmail }
238251
}
239252
```
240253
</Tab>
@@ -257,9 +270,11 @@ This guide will show you how to customize a session token to include additional
257270
return json({ error: 'Unauthorized' }, { status: 401 })
258271
}
259272

260-
const metadata = sessionClaims.metadata
273+
const fullName = sessionClaims.fullName
274+
275+
const primaryEmail = sessionClaims.primaryEmail
261276

262-
return json({ metadata })
277+
return json({ fullName, primaryEmail })
263278
},
264279
})
265280
```
@@ -275,14 +290,15 @@ This guide will show you how to customize a session token to include additional
275290
1. Create the `CustomJwtSessionClaims` interface and declare it globally.
276291
1. Add the custom claims to the `CustomJwtSessionClaims` interface.
277292
278-
The following example demonstrates how to add the `metadata` claim to the `CustomJwtSessionClaims` interface.
293+
The following example demonstrates how to add the `fullName` and `primaryEmail` claims to the `CustomJwtSessionClaims` interface.
279294
280295
```tsx {{ filename: 'types/globals.d.ts' }}
281296
export {}
282297

283298
declare global {
284299
interface CustomJwtSessionClaims {
285-
metadata: string
300+
fullName: string
301+
primaryEmail: string
286302
}
287303
}
288304
```

docs/backend-requests/resources/session-tokens.mdx

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,9 @@ You can also create custom tokens using a [JWT template](/docs/backend-requests/
9898

9999
## Size limitations
100100

101-
The Clerk session token is stored in a cookie. All modern browsers [limit the maximum size of a cookie to **4KB**](https://datatracker.ietf.org/doc/html/rfc2109#section-6.3). Exceeding this limit can have adverse effects, such as possible infinite redirect loops in Next.js applications.
101+
Clerk stores the session token in a cookie, and [**most browsers limit cookie size to 4KB**](https://datatracker.ietf.org/doc/html/rfc2109#section-6.3). Exceeding this limit will cause the cookie to not be set, which will break your app as Clerk depends on cookies to work properly.
102102

103-
A session token with the [default session claims](#default-claims) won't run into this issue, as this configuration produces a cookie significantly smaller than 4KB. However, this limitation becomes relevant when implementing a [custom session token](/docs/backend-requests/custom-session-token). **It's recommended to keep the total size of custom claims in the session token under 1.2KB.**
103+
A session token with the [default session claims](#default-claims) won't run into this issue, as this configuration produces a cookie significantly smaller than 4KB. However, you must consider this limit when implementing a [custom session token](/docs/backend-requests/custom-session-token). After accounting for the size of Clerk's default claims, the cookie can support **up to 1.2KB** of custom claims.
104104

105105
Claims to monitor for size limits:
106106

@@ -110,14 +110,14 @@ Claims to monitor for size limits:
110110
- `org.public_metadata`
111111
- `org_membership.public_metadata`
112112

113-
If you add any of these custom claims in your token, use caution to ensure the stored data doesn't exceed the size limit. It's recommended to [move particularly large claims like these out of the token](#example) and fetch them using a separate API call from your backend.
113+
If you add any of these custom claims in your token, use caution to ensure the stored data doesn't exceed the size limit. It's highly recommended to [store the extra data in your own database](/docs/webhooks/sync-data#storing-extra-user-data) instead of storing it in metadata in the session token. If this isn't an option, you can [move particularly large claims like these out of the token](#example) and fetch them using a separate API call from your backend.
114114

115115
> [!NOTE]
116116
> If your application encounters this issue, the Clerk Dashboard will display a warning: **"Some users are exceeding cookie size limits"**. To resolve this, update your [custom session token](/docs/backend-requests/custom-session-token).
117117
118118
### Example
119119

120-
It's recommended to keep the total size of custom claims in the session token under 1.2KB. Move particularly large claims out of the session token and fetch them using a separate API call from your backend.
120+
It's recommended to keep the total size of custom claims in the session token under 1.2KB. The following example shows how to move particularly large claims out of the session token and fetch them using a separate API call from your backend. The limitations of this approach are that if you make this call to Clerk's Backend API frequently, you risk hitting [rate limits](/docs/backend-requests/resources/rate-limits) and it's also slower than making a database query. We highly recommend [storing the extra data in your own database](/docs/webhooks/sync-data#storing-extra-user-data) instead of storing it in metadata in the session token.
121121

122122
For example, if you were storing several fields in `user.public_metadata`, like this:
123123

@@ -343,8 +343,6 @@ If you need to access the other fields, you can fetch them using a separate API
343343
</Tab>
344344
</Tabs>
345345

346-
However, if you make this call to Clerk's Backend API frequently, you risk hitting [rate limits](/docs/backend-requests/resources/rate-limits) and it's also slower than making a database query. So it's recommended to [store the extra data in your own database](/docs/webhooks/sync-data#storing-extra-user-data) instead of storing it in metadata in the session token.
347-
348346
## Validate session tokens
349347

350348
If you're using the middleware provided by our Clerk SDKs, validating session tokens is handled automatically in every request. If you're not using the middleware, you can still use the respective helpers provided by the SDKs to validate the tokens.

0 commit comments

Comments
 (0)