I am not able to get jwt token from cookies while authorization some pages.?

Viewed 641

I have created a MERN application in that application whenever try to login in application jwt token is generated each time whenever he/she tries to log in and stored inside the MongoDB atlas as well as browser cookies. In the authorization part, if a user is authorized (cookies token matches with the MongoDB token) then he/she can see only the about-me page or else be redirected to the login page.

so whenever I clicked to about-me page I got err:

TypeError: Cannot read properties of undefined (reading 'jwtoken')
    at Authenticate (/Users/apple/Desktop/projects/mern-auth-user/user-data-123/mern-july1/server/middleware/authenticate.js:8:35)
    at Layer.handle [as handle_request] (/Users/apple/Desktop/projects/mern-auth-user/user-data-123/mern-july1/server/node_modules/express/lib/router/layer.js:95:5)
 error so on....   

here; How I created sign API and stored token into MongoDB and cookies. (in auth.js)

router.post("/signin", async (req, res) => {
  const { email, password } = req.body;

  if (!email || !password) {
    return res.status(400).json({ err: "invalid details" });
  }
  try {
    const userLogin = await User.findOne({ email: email });
    // console.log(userLogin);

    if (!userLogin) {
      res.status(400).json({ err: "invalid email" });
    } 
    else {
      const isMatch = await bcrypt.compare(password, userLogin.password);

      // jwt token
      const token = await userLogin.generateAuthToken();

      res.cookie("jwtoken", token, {
        expires : new Date(Date.now()+25892000000),          // after 30 days
        httpOnly: true
      });
      
      console.log(token);

      if(!isMatch){
        res.status(400).json({err: 'invalid pass'})
      }
      else{
        res.status(201).json({message:'signin successfully'})
        console.log(userLogin)
      }
     
    }
  } catch (err) {
    console.log(err);
  }
});

generateAuthToken defined inside the user schema modal used inside the signin API.

userSchema.methods.generateAuthToken = async function(){
    try{
        const token = jwt.sign({_id : this._id}, process.env.SECRET_KEY);  // _id(asking unique id) : this._id (taken id from database of corresponding login email)
        this.tokens = this.tokens.concat({token : token})                  // storing jwt token into tokens. token(from userSchema) : token (value from generated token)
        await this.save();
        return token;

    }
    catch(err){
        console.log(err);
    }
}

this is my middleware "Authenticate"

const jwt = require('jsonwebtoken');
const User = require('../models/userSchema');


const Authenticate = async (req, res, next) => {
    try {
        //get jwt token from cookies
        const token = req.cookies.jwtoken;
        //verifying token with SECRET_KEY
        const verifyToken = jwt.verify(token, process.env.SECRET_KEY);
        // get user data from token, if token id(from cookies)===tokens.token
        const rootUser = await User.findOne({ _id: verifyToken._id, "tokens.token": token });

        if (!rootUser) { throw new Error('user not found') }
        // if get user
        req.token = token;
        // get user's all data in rootUser
        req.rootUser = rootUser;
        // get id od rootUser
        req.userID = rootUser._id;

        next();
    }
    catch (err) {
        res.status(401).send("unauthorized: no token provided")
        console.log(err)
    }
}

module.exports = Authenticate;

used inside the about-me API; auth.js


router.get('/about', authenticate, (req, res) => {
  // console.log(Authenticate.token)
        res.send('hello world from server side');
        res.send(req.rootUser)
})

now code inside the Reactjs About.js

    const history = useHistory();

    const callAboutPage = async () =>{
        try{
            const res = await fetch('/about', {           //this res is backend response , not from call back function
                method: "GET",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json"
                },
                credentials: "include"
            });
            const data = await res.json();
            console.log(data)
            if(! res.status === 200){
                const error = new Error(res.error);
                throw error;
            }
        }
        catch(err){
            console.log(err)
            history.push('/signin');
        }
    };

    useEffect(() => {
        callAboutPage()
    }, [])

These is my cookies stored in the browser enter image description here

please help me to get the about-me page right now I am not able to see my page even I have cookies inside my application(browser).

1 Answers

Cannot read properties of undefined (reading 'jwtoken') indicates that req.cookies is undefined in Authenticate.js.

You may miss the middleware cookie-parser for express, check express doc (req.cookies) here.

To fix this, follow the example of cookie-parser (npm) would help. Code like below will allow you to read cookies from req.cookies.

const cookieParser = require('cookie-parser');

const app = express();
app.use(cookieParser());
Related