Using the Payload Auth Middleware
Because Payload uses your existing Express server, you are free to add whatever logic you need to your app through endpoints of your own. However, Payload does not add its middleware to your Express app itself—instead, it scopes all of its middleware to Payload-specific routers.
This approach has a ton of benefits - it's great for isolation of concerns and limiting scope, but it also means that your additional routes won't have access to Payload's user authentication.
You can make full use of Payload's built-in authentication within your own custom Express
endpoints by adding Payload's authentication middleware.
Payload must be initialized before the payload.authenticate
middleware can be used. This is done
by calling payload.init()
prior to adding the middleware.
Example in server.js
:
1import express from 'express'
2import payload from 'payload'
6const start = async () => {
8 secret: 'PAYLOAD_SECRET_KEY',
12 const router = express.Router()
15 router.use(payload.authenticate)
17 router.get('/', (req, res) => {
19 return res.send(`Authenticated successfully as ${req.user.email}.`)
22 return res.send('Not authenticated')
25 app.use('/some-route-here', router)
Versions