#TypeScript error when using the Payload Auth Middleware in custom express routes

2 messages · Page 1 of 1 (latest)

real spear
#

I'm implementing a custom routes that use the payload auth middleware, like in this example.

https://payloadcms.com/docs/authentication/using-middleware

But I'm getting a TypeScript error when accessing req.user: Property 'user' does not exist on type 'Request<{}, any, any, ParsedQs, Record<string, any>>'

Is there a recommended way to get the types to place nicely?

My code:

import express from 'express'
import payload from 'payload'

require('dotenv').config()
const app = express()

// Redirect root to Admin panel
app.get('/', (_, res) => {
  res.redirect('/admin')
})

const start = async () => {
  await payload.init({
    secret: process.env.PAYLOAD_SECRET || 'supersecret',
    mongoURL: process.env.MONGODB_URI || 'mongodb://localhost/cms',
    express: app,
    onInit: async () => {
      payload.logger.info(`Payload Admin URL: ${payload.getAdminURL()}`)
    }
  })

  const router = express.Router()

  // Note: Payload must be initialized before the `payload.authenticate` middleware can be used
  router.use(payload.authenticate)

  router.get('/', (req, res) => {
    if (req.user) {
      return res.send(`Authenticated successfully as ${req.user.email}.`)
    }

    return res.send('Not authenticated')
  })

  app.use('/some-route-here', router)

  // Add your own express routes here

  app.listen(process.env.PORT || process.env.PAYLOAD_LOCAL_PORT)
}

start()
Payload CMS

Payload is a headless CMS and application framework built with TypeScript, Node.js, React and MongoDB

velvet rootBOT