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.
Example in server.js
:
1
import express from 'express'
2
import payload from 'payload'
3
4
const app = express()
5
6
const start = async () => {
7
await payload.init({
8
secret: 'PAYLOAD_SECRET_KEY',
9
express: app,
10
})
11
12
const router = express.Router()
13
14
// Note: Payload must be initialized before the `payload.authenticate` middleware can be used
15
router.use(payload.authenticate)
16
17
router.get('/', (req, res) => {
18
if (req.user) {
19
return res.send(`Authenticated successfully as ${req.user.email}.`)
20
}
21
22
return res.send('Not authenticated')
23
})
24
25
app.use('/some-route-here', router)
26
27
app.listen(3000)
28
}
29
30
start()
Next