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
}
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
}
Next