Search code examples
javascriptnode.jsexpressexpress-jwt

Problem with import variable in express, Error: Route.get() requires a callback function


I try to import requireSignin from controllers/auth.js file to routes/user.js file and put it in the router.get('/user/:id', requireSignin, read); route.

I have the following error:

Error: Route.get() requires a callback function but got a [object Undefined]

controllers/auth.js

const expressJwt = require('express-jwt');

exports.requireSignin = expressJwt({
    secret: process.env.JWT_SECRET
});

routes/user.js

const express = require('express');
const router = express.Router();

const {requireSignin} = require('../controllers/auth');
const {read} = require('../controllers/user');

router.get('/user/:id', requireSignin, read);

module.exports = router;

But if I don't import it, only I do it in another way, directly in one file routes/user.js. It works very well.

routes/user.js

const express = require('express');
const router = express.Router();
const expressJwt = require('express-jwt');

const {read} = require('../controllers/user');

router.get('/user/:id', expressJwt({
    secret: process.env.JWT_SECRET
}), read);

module.exports = router;

Solution

  • The error is quite clear to me. Please try to confirm it with a debugger (a severely underappreciated tool among the StackOverflow users), but it looks like the line const {requireSignin} = require('../controllers/auth'); initializes the requireSignin with undefined instead of middleware function. There can be several reasons for this. Perhaps your IDE adds some parameter to node that prevents it from accepting the notation exports.requireSignin and you actually have to specify it as module.exports.requireSignin. If that's not it, assuming this is not the full version of your code and just simplified few lines to highlight the problem, make sure you don't have any typos between your import and export.