Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Token Data

During the lifecycle of a request you will be able to access the data you have configured to be stored in the JWT by accessing req.user. The user object is automatically appended to the request for you.

Defining Token Data

You can specify what data gets encoded to the Cookie/JWT-Token by setting saveToJWT property on fields within your auth collection.

1
import type { CollectionConfig } from 'payload'
2
3
export const Users: CollectionConfig = {
4
slug: 'users',
5
auth: true,
6
fields: [
7
{
8
// will be stored in the JWT
9
saveToJWT: true,
10
type: 'select',
11
name: 'role',
12
options: ['super-admin', 'user'],
13
},
14
{
15
// the entire object will be stored in the JWT
16
// tab fields can do the same thing!
17
saveToJWT: true,
18
type: 'group',
19
name: 'group1',
20
fields: [
21
{
22
type: 'text',
23
name: 'includeField',
24
},
25
{
26
// will be omitted from the JWT
27
saveToJWT: false,
28
type: 'text',
29
name: 'omitField',
30
},
31
],
32
},
33
{
34
type: 'group',
35
name: 'group2',
36
fields: [
37
{
38
// will be stored in the JWT
39
// but stored at the top level
40
saveToJWT: true,
41
type: 'text',
42
name: 'includeField',
43
},
44
{
45
type: 'text',
46
name: 'omitField',
47
},
48
],
49
},
50
],
51
}

The JWT keys id, collection, email, sid, iat, and exp are reserved for Payload. A custom string passed to saveToJWT cannot replace these keys.

Payload signs an authVersion: 1 marker in each token's protected JWT header. This identifies tokens issued by the fixed authentication format. Tokens issued before this protection was added do not have the marker and must be replaced by signing in again; integrations must also reissue stored bearer tokens. The decoded JWT payload remains flat and keeps fields configured with saveToJWT at the same paths, and /me returns the same data for a valid new token. The version marker is not a payload field.

Using Token Data

This is especially helpful when writing Hooks and Access Control that depend on user defined fields.

1
import type { CollectionConfig } from 'payload'
2
3
export const Invoices: CollectionConfig = {
4
slug: 'invoices',
5
access: {
6
read: ({ req, data }) => {
7
if (!req?.user) return false
8
if ({ req.user?.role === 'super-admin'}) {
9
return true
10
}
11
return data.owner === req.user.id
12
}
13
}
14
fields: [
15
{
16
name: 'owner',
17
relationTo: 'users'
18
},
19
// ... other fields
20
],
21
}

Was this page helpful?

Next

Rich Text Editor