Repository navigation
TypeError: Router.use() requires a middleware function but got a Object #6284
|
TypeError: Router.use() requires a middleware function but got a Object setReqUser.ts import { Request, Response, NextFunction } from 'express'; interface DecodedToken { export default async function setReqUser (req: Request, res: Response, next: NextFunction) { } catch (error) { next(); |
Replies: 2 comments
|
Hi, Could you please provide a reproduce-able codebase? It would be helpful for the folks answering the question. |
|
1. You called the middleware instead of passing it
// wrong — passes a Promise
app.use(setReqUser())
// right — passes the function
app.use(setReqUser)This is the most common cause with 2. You mounted the module object (CJS / default export)// CommonJS: this is `{ default: [Function] }`, not the function
const setReqUser = require('./middleware/setReqUser')
app.use(setReqUser)
// use the function
app.use(setReqUser.default)With ESM, keep a default import matching the default export: import setReqUser from './middleware/setReqUser.js'
app.use(setReqUser)
3.
|
Router.use() requires a middleware function but got an Objectis a runtime error: Express received something that is not a function. ThesetReqUsersource you posted is a function, so the bug is almost always at the call site or in the module interop, not in the JWT logic.1. You called the middleware instead of passing it
setReqUserisasync. Calling it returns a Promise, and a Promise is an object:This is the most common cause with
asyncmiddleware.2. You mounted the module object (CJS / default export)