[Fixed] Not able to store json web token in cookies in my browser

Issue

So i was learning about JWT authentication for user login in MERN project using cors npm.I am able to generate the jwt and also able to store it in the DB , but i am not able to see my cookie being stored in the browser.

This is my generateAuthToken() function present in the schema file in express server, here i am generating a jwt & returning it –

userSchema.methods.generateAuthToken = async function(){
try{
        //generate token
        const token = jwt.sign({_id:this._id.toString()} , process.env.SECRET_KEY);
        
        //stored the generated token in our document
        this.tokens = this.tokens.concat({token : token});

        //saved the changes made in the document
        await this.save();

        //returning the token generated when called
        return token;

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

}

and calling the generateAuthtoken() function in the index.js present in express server.The returned token is stored in the ‘token’ –

const token = await userLogin.generateAuthToken();
        //console.log(token);


    //storing logged in tokens inside cookies
        res.cookie("logintoken" , token , {
            expires : new Date(Date.now() + 60000), //60sec from the time we store the token inside the cookie
            httpOnly : true
        });

And in the frontend react code , i am sending a credentials header inside fetch api , which calls to login route present in my express server at port 4000 –

const response = await fetch('http://localhost:4000/login',{
                method : "POST",
                credentials: 'include',
                headers : {
                    "Content-Type" : "application/json"
                },
                body : JSON.stringify({
                        email : email,
                        password : password
                })
        });

I am using cors npm package for cross-region requests in my express server –

   const cors = require('cors');

   app.use(cors());

And in my browser console ,i am facing this error –

enter image description here

but when i check in my browser , cookie is not getting stored in the storage –

enter image description here

To summarise , i am generating a jwt and returning it inside the function.Then storing that returned token inside a cookie named ‘logintoken’.But that cookie is not getting stored in the browser.

I was researching on this and was able to find some threads stating that we also have to define some headers in cors so that the browser is able to store the cookie.But i was not able to figure out how to add as well as which headers are required to achieve this.I have worked before with cookies & jwt , but this is my first time learning with react , express & cors npm.Thank you for your response.

Solution

here is a code snippet from my current app

app.use(
    cors({
        credentials: true,
        origin: `http://${process.env.REACT_APP_SERVER_HOST}:${process.env.PORT}`,
    })
);

Leave a Reply

(*) Required, Your email will not be published