Skip to content

Commit 5a56db0

Browse files
committed
apply code review suggestions
1 parent 38dcbdf commit 5a56db0

File tree

8 files changed

+86
-69
lines changed

8 files changed

+86
-69
lines changed
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
> [!WARNING]
22
> Metadata is limited to **8KB** maximum. If you're storing metadata as a custom claim in the session token, it's highly recommended to keep it under **1.2KB**. [Learn more about the session token size limitations](/docs/backend-requests/resources/session-tokens#size-limitations).
33
>
4-
> If you use Clerk metadata and modify it server-side, the changes won't appear in the session token until the next refresh. To avoid race conditions, either force a JWT refresh after metadata changes or handle the delay in your application logic.
4+
> If you use Clerk metadata and modify it server-side, the changes won't appear in the session token until the next refresh. To avoid race conditions, either [force a JWT refresh](/docs/guides/force-token-refresh) after metadata changes or handle the delay in your application logic.
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 & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -17,22 +17,20 @@ 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>
3232
For Next.js, the `Auth` object is accessed using the `auth()` helper in App Router apps and the `getAuth()` function in Pages Router apps. [Learn more about using these helpers](/docs/references/nextjs/read-session-data#server-side).
3333

34-
Use the following tabs to see examples of how to use these helpers to access the user's ID in your App Router or Pages Router app.
35-
3634
<CodeBlockTabs options={["App Router", "Pages Router"]}>
3735
```tsx {{ filename: 'app/api/example/route.tsx' }}
3836
import { auth } from '@clerk/nextjs/server'
@@ -41,9 +39,11 @@ This guide will show you how to customize a session token to include additional
4139
export async function GET() {
4240
const { sessionClaims } = await auth()
4341

44-
const metadata = sessionClaims?.metadata
42+
const fullName = sessionClaims.fullName
43+
44+
const primaryEmail = sessionClaims.primaryEmail
4545

46-
return NextResponse.json({ metadata })
46+
return NextResponse.json({ fullName, primaryEmail })
4747
}
4848
```
4949

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

58-
const metadata = sessionClaims.metadata
58+
const fullName = sessionClaims.fullName
5959

60-
return res.status(200).json({ metadata })
60+
const primaryEmail = sessionClaims.primaryEmail
61+
62+
return res.status(200).json({ fullName, primaryEmail })
6163
}
6264
```
6365
</CodeBlockTabs>
@@ -78,9 +80,11 @@ This guide will show you how to customize a session token to include additional
7880
return new Response('Unauthorized', { status: 401 })
7981
}
8082

81-
const metadata = sessionClaims.metadata
83+
const fullName = sessionClaims.fullName
84+
85+
const primaryEmail = sessionClaims.primaryEmail
8286

83-
return new Response(JSON.stringify({ metadata }))
87+
return new Response(JSON.stringify({ fullName, primaryEmail }))
8488
}
8589
```
8690
</Tab>
@@ -102,9 +106,11 @@ This guide will show you how to customize a session token to include additional
102106
const getSessionClaims = (req, res, next) => {
103107
const { sessionClaims } = getAuth(req)
104108

105-
const metadata = sessionClaims.metadata
109+
const fullName = sessionClaims.fullName
106110

107-
return res.status(200).json({ metadata })
111+
const primaryEmail = sessionClaims.primaryEmail
112+
113+
return res.status(200).json({ fullName, primaryEmail })
108114
}
109115

110116
app.get('/profile', requireAuth(), getSessionClaims)
@@ -133,7 +139,8 @@ This guide will show you how to customize a session token to include additional
133139
)
134140

135141
type CustomSessionClaims struct {
136-
metadata string `json:"metadata"`
142+
FullName string `json:"fullName"`
143+
PrimaryEmail string `json:"primaryEmail"`
137144
}
138145

139146
func customClaimsConstructor(ctx context.Context) any {
@@ -172,7 +179,7 @@ This guide will show you how to customize a session token to include additional
172179
if !ok {
173180
// Handle the error how you see fit
174181
} else {
175-
fmt.Fprintf(w, `{"public_metadata": "%s"}`, customClaims.metadata)
182+
fmt.Fprintf(w, `{"full_name": "%s", "primary_email": "%s"}`, customClaims.FullName, customClaims.PrimaryEmail)
176183
}
177184
}
178185
```
@@ -196,19 +203,21 @@ This guide will show you how to customize a session token to include additional
196203
return redirect('/sign-in?redirect_url=' + args.request.url)
197204
}
198205

199-
const metadata = sessionClaims.metadata
206+
const fullName = sessionClaims.fullName
207+
208+
const primaryEmail = sessionClaims.primaryEmail
200209

201210
return {
202-
metadata,
211+
fullName: JSON.stringify(fullName),
212+
primaryEmail: JSON.stringify(primaryEmail),
203213
}
204214
}
205215

206216
export default function Profile({ loaderData }: Route.ComponentProps) {
207217
return (
208218
<div>
209-
<p>
210-
Welcome {userId}, your public metadata is {loaderData.metadata}
211-
</p>
219+
<p>Welcome {loaderData.fullName}</p>
220+
<p>Your email is {loaderData.primaryEmail}</p>
212221
</div>
213222
)
214223
}
@@ -232,9 +241,11 @@ This guide will show you how to customize a session token to include additional
232241
return redirect('/sign-in?redirect_url=' + args.request.url)
233242
}
234243

235-
const metadata = sessionClaims.metadata
244+
const fullName = sessionClaims.fullName
236245

237-
return { metadata }
246+
const primaryEmail = sessionClaims.primaryEmail
247+
248+
return { fullName, primaryEmail }
238249
}
239250
```
240251
</Tab>
@@ -257,9 +268,11 @@ This guide will show you how to customize a session token to include additional
257268
return json({ error: 'Unauthorized' }, { status: 401 })
258269
}
259270

260-
const metadata = sessionClaims.metadata
271+
const fullName = sessionClaims.fullName
272+
273+
const primaryEmail = sessionClaims.primaryEmail
261274

262-
return json({ metadata })
275+
return json({ fullName, primaryEmail })
263276
},
264277
})
265278
```
@@ -275,14 +288,15 @@ This guide will show you how to customize a session token to include additional
275288
1. Create the `CustomJwtSessionClaims` interface and declare it globally.
276289
1. Add the custom claims to the `CustomJwtSessionClaims` interface.
277290

278-
The following example demonstrates how to add the `metadata` claim to the `CustomJwtSessionClaims` interface.
291+
The following example demonstrates how to add the `fullName` and `primaryEmail` claims to the `CustomJwtSessionClaims` interface.
279292

280293
```tsx {{ filename: 'types/globals.d.ts' }}
281294
export {}
282295

283296
declare global {
284297
interface CustomJwtSessionClaims {
285-
metadata: string
298+
fullName?: string
299+
primaryEmail?: string
286300
}
287301
}
288302
```

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)