Vivek Jeevanarajh
Vivek Jeevanarajh

Reputation: 13

how to add authentication middleware in node js

I create user service with login and register in node js. when i using authenticate middleware i got this kind of errors. if any one have solution. please let me know. i attached code and error image.

this is my route file.

const { Router} = require('express');

const authController = require('../controllers/authController');
const {authMiddleware} = require('../middleware/authMiddleware')

const router = Router();

router.get('/users',{authMiddleware}, authController.users_get);
router.post('/users',authController.users_post);
router.post('/authenticate',authController.authenticate_post);


module.exports = router;

this is my middleware file

const jwt = require('jsonwebtoken');

const requireAuth =(req, res, next)=>{
    const token = req.cookie.jwt;

    //check json web token exists & is verified


    if(token){
        jwt.verify(token,'vivekeviv',(err, decodedToken)=>{
            if (err){
                console.log(err)
            }
            else {
                console.log(decodedToken);
                next();
            }
        })
    }
    else {

        console.log("You need to login")

    }
}

module.exports ={requireAuth}


how to add middleware to this code.

i got this kind of error. error image

Upvotes: 0

Views: 2940

Answers (1)

Christian Fritz
Christian Fritz

Reputation: 21364

You are passing an object where express is expecting a function. You want:

const {requireAuth} = require('../middleware/authMiddleware')
...
router.get('/users', requireAuth, authController.users_get);

Upvotes: 1

Related Questions