'When I am trying get cookies it gives me error as -> TypeError: Cannot read property 'token' of undefined

I have created jwt token as follows:

const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
 
const userSchema = new mongoose.Schema({
    firstName: {
        type: String,
        required:true
    },
    lastName: {
        type: String,
        required:true
    },
    email: {
        type: String,
        required:true
    },
    password: {
        type: String,
        required:true
    },
    tokens:[
        {
            token: {
                type: String,
                required:true
            }
        }
    ]
});

userSchema.methods.generateAuthToken = async function () {
    try{

        let token = jwt.sign({_id: this._id}, process.env.SECRET_KEY);
        this.tokens = this.tokens.concat({token: token});
        await this.save();
        return token;
    }catch(err) {
        console.log(err);
    }
}

const User = mongoose.model('USER', userSchema);

module.exports = User;

and saved this token in the format of cookie when user successfully login as follow :

const jwt = require('jsonwebtoken');
const express = require('express');
const bcrypt = require('bcrypt');
const router = express.Router();
const app = express();
const cookieParser = require('cookie-parser');

const userAuthenticate = require("../middleware/UserAuthenticate");

require('../db/conn');
const User = require("../model/userSchema");
 
    router.post('/signin', async (req, res) => {
        try{
            const {email, password} = req.body;
    
            if(!email || !password){
                return res.status(400).json({error: "please fill the data"});
            }
    
            const userLogin = await User.findOne({ email: email });
    
            if(userLogin){
                const isMatch = await bcrypt.compare(password, userLogin.password);
    
                const token = await userLogin.generateAuthToken();
    
                res.cookie('signintoken', token, {
                    expires:new Date(Date.now() + 25892000000),
                    httpOnly:true
                });
    
                if(!isMatch){
                    res.status(400).json({error: "user invalid pass"});
                }else{
                    res.json({ message: "user signin successfully"});
            }            
            }else{
                res.status(400).json({error: "user invalid"});             
            }
            
        } catch(err){
             console.log(err);  
            }
    });

after storing the jwt token as a cookie on the website I want to get the cookie in my JS as below :

router.get('/userprofile', userAuthenticate, async (req, res) =>{
    res.send(req.rootUser);
    console.log(req.token) // it gives error as I mentioned below.
});

here is the code of userAuthenticate function as I mentioned above as middleware for getting cookie :

const Express = require('express');
const jwt = require('jsonwebtoken');
const User = require("../model/userSchema");
const dotenv = require('dotenv');
const app = Express();

dotenv.config({path: './config.env'});

const cookieParser = require('cookie-parser');
app.use(cookieParser());

const UserAuthenticate = async (req, res, next) => {
    try{
        const token = req.cookies.signintoken;
        console.log(token); // it prints 'undefined' on console.
        const verifyToken = jwt.verify(token, process.env.SECRET_KEY);

        const rootUser = await User.findOne({_id: verifyToken._id, "tokens.token": token });

        if(!rootUser) { 
            throw new Error('User not found');
        }       
        else{
            res.status(500).send('user found');
        }

        req.token = token;
        req.rootUser = rootUser;
        req.userID = rootUser._id;

        next();

    }catch(err){
        res.status(401).send('Unauthorized: No token provided');
        console.log(err);
    }
}

module.exports = UserAuthenticate;

As I am trying to fetch cookie,

my postman response is :

{ Unauthorized: No token provided }

and my console o/p is :

TypeError: Cannot read property 'signintoken' of undefined
    at UserAuthenticate (D:\Web Development Projects\Web_Projects\MERN Projects\hotdeals\backend\middleware\UserAuthenticate.js:15:35)
    at Layer.handle [as handle_request] (D:\Web Development Projects\Web_Projects\MERN Projects\hotdeals\backend\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\Web Development Projects\Web_Projects\MERN Projects\hotdeals\backend\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\Web Development Projects\Web_Projects\MERN Projects\hotdeals\backend\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (D:\Web Development Projects\Web_Projects\MERN Projects\hotdeals\backend\node_modules\express\lib\router\layer.js:95:5)
    at D:\Web Development Projects\Web_Projects\MERN Projects\hotdeals\backend\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (D:\Web Development Projects\Web_Projects\MERN Projects\hotdeals\backend\node_modules\express\lib\router\index.js:341:12)
    at next (D:\Web Development Projects\Web_Projects\MERN Projects\hotdeals\backend\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (D:\Web Development Projects\Web_Projects\MERN Projects\hotdeals\backend\node_modules\express\lib\router\index.js:174:3)
    at router (D:\Web Development Projects\Web_Projects\MERN Projects\hotdeals\backend\node_modules\express\lib\router\index.js:47:12)


Solution 1:[1]

In your router file, write this:

const cookieParser = require("cookie-parser")

Then add:

router.use(cookieParser());

and remove same this code from your App.js file.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tyler2P