Search code examples
expresscookiessession-cookies

req.cookies not working in express js (cookie-parser package)


i am using cookie parser in express to store the token in cookie and access it later, the token is stored in the cookie but i am unable to access it using req.cookies here is sambles of my codes

package.json

{  
  "type": "module",
   ...
  "dependencies": {
    ...
    "cookie-parser": "~1.4.4",
    ...
  },
  "devDependencies": {
    "@types/cookie-parser": "^1.4.3",
    ...
  }

index.js


import cookieParser from "cookie-parser";
...

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

when login

    ...
    res.cookie("refreshToken", refreshToken, {
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 100,
    });
    ...

for accessing the cookie

 const response = await axios.get(
        "http://localhost:5000/token",
        { withCredentials: true }
      );
// -----------------------
// and at the /token I have this function

    const refreshToken = req.cookies.refreshToken;
    if (!refreshToken) {
      return res.status(401).json({msg: refreshToken});
    }
    ...

when trying to access the cookie using

    const refreshToken = req.cookies.refreshToken;
    if (!refreshToken) {
      return res.sendStatus(401);
    }
    ...

the if condition always true i tried to console.log(req.cookies.refreshToken) but it says undefined this was the last task i needed to finish my project please help thank you


Solution

  • I tried this and worked for me for some reason:

    try {
      axios.defaults.withCredentials = true;
    
      const response = await axios.get(
        "http://localhost:5000/collections/token"
      );
      ...
    } catch (error) {
      ...
    }
    

    And the core and the login is still the same:

    // the core at index.js
    app.use(cors({ credentials: true, origin: "http://localhost:3000" }));
        
    // login js 
    res.cookie("refreshToken", refreshToken, {
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 100,
    });