docs/authentication/jwt.mdx
Payload offers the ability to Authenticate via JSON Web Tokens (JWT). These can be read from the responses of login, logout, refresh, and me auth operations.
In addition to authenticating via an HTTP-only cookie, you can also identify users via the Authorization header on an HTTP request.
Example:
const user = await fetch('http://localhost:3000/api/users/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: '[email protected]',
password: 'password',
}),
}).then((req) => await req.json())
const request = await fetch('http://localhost:3000', {
headers: {
Authorization: `JWT ${user.token}`,
},
})
In some cases you may want to prevent the token from being returned from the auth operations. You can do that by setting removeTokenFromResponses to true like so:
import type { CollectionConfig } from 'payload'
export const UsersWithoutJWTs: CollectionConfig = {
slug: 'users-without-jwts',
auth: {
removeTokenFromResponses: true, // highlight-line
},
}
When validating Payload-generated JWT tokens in external services, use the processed secret rather than your original secret key:
import crypto from 'node:crypto'
const secret = crypto
.createHash('sha256')
.update(process.env.PAYLOAD_SECRET)
.digest('hex')
.slice(0, 32)