skip to Main Content

i use expessJS, cookiePaser and try access cookie but it always return undefined eventhough it has been set on browser

this is options cors

app.use(
    cors({
        origin: "http://localhost:3000",
        credentials: true,
    })
);
app.use(cookieParser());

this is fetch

const res = await fetch("http://localhost:3001/api/auth/signin", {
            method: "POST",
            credentials: 'include',
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(formData),
        });

this is set cookie

res.cookie("access_token", token, {
            httpOnly: true,
            expires: new Date(Date.now() + 24 * 60 * 60 * 1000),
            sameSite: 'None',
        })

this is access cookie

export const verifyToken = (req, res, next) => {
const token = req.cookies.access_token;
console.log(token);
if(!token) {
    return next(errorHandler(401, 'Unauthorized!!'));
}
jwt.verify(token, process.env.JWT_SECRET, (error, user) => {
    if(error) return next(errorHandler(401, "Forbidden!!"));
    req.user = user;
})
next();

}

Every time I access the cookie it returns undefined.

2

Answers


  1. If the intention is to access the cookies via Javascript on the frontend specifying a cookie as httpOnly will prevent this. httpOnly is an added layer of security to help prevent cross site scripting attacks.

    Express gives you some information in their documentation about the various different properties you can apply to a cookie.

    In your case, if you do want to access the cookie via javascript you would have to remove the httpOnly property from res.cookie like so

    res.cookie("access_token", token, {
                expires: new Date(Date.now() + 24 * 60 * 60 * 1000),
                sameSite: 'None',
            })
    

    To access the cookie on the backend, you need to make sure you’re able to parse the cookies. Install a relevant parser to retrieve the cookies. For example,
    npm install cookie-parser

    Then. You’d want to set the middleware in your express application. And then finally retrieve the cookie in the endpoint 🙂

    
    const express = require('express');
    const cookieParser = require('cookie-parser');
    const app = express();
    const port = 3000;
    
    // cookie-parser middleware
    app.use(cookieParser());
    
    app.get('/some_endpoint', (req, res) => {
        // Access the access_token cookie
        const access_token = req.cookies.access_token;
    
        // rest of your logic
    });
    
    app.listen(port, () => {
        console.log(`Server running at http://localhost:${port}`);
    });
    
    
    Login or Signup to reply.
  2. … If you are setting SameSite=None it must always be Secure. If you do not set Secure, the cookie will be rejected.

    Citation : Will a cookie whose samesite=none and secure=true not set from Chrome 80?

    The code does the same, it sets SameSite None still Secure is not set. Thanks to @CBroe for the same he has quoted from MDN.

    Therefore please remove sameSite: ‘Non’ if you are in http, or set Secure if you are in https.

    res.cookie("access_token", token, {
            httpOnly: true,
            expires: new Date(Date.now() + 24 * 60 * 60 * 1000),
            sameSite: 'None',
        })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search