1

I'm sending cookies from express server (res.cookie()) but this ain't working with my front end even though I include {withCredentials:true} in the get requests but it just doesn't work in the browser, no cookies are set in the application tab in browser. BUT if I try the requests with postman the middleware works perfectly and cookies are shown. I tried different browsers and different devices, but none. cors config:

app.use(
  cors({
  
    credentials: true,
    origin: [
      "http://localhost:3000", 
    ],
    methods: ["GET", "POST"],

  })
);

cookie parser config:

app.use(cookieParser())

this is the get request to check if the user is already logged in :

    await axios
        .get("http://192.168.0.141:3001/login", { withCredentials: true })
        .then(async (response) => {

            if (response) {
                loggedIn = true
            }
        })
        .catch(async err => {

            loggedIn = false
        })

the middleware of jwt :

const validateToken = (req, res, next) => {
    const accessToken = req.cookies["access-token"]
    if (!accessToken) { return res.status(400).json({ error: "user not authenticated" }) }
    try {
        const validToken = jwt.verify(accessToken, "test");
        if (validToken) {
            req.authenticated = true
            return next();
        }
    } catch (error) {
        return res.status(400).json({ error: error });
    }
}

If you need more clarification please tell me , thank you for helping

Firas SCMP
  • 461
  • 4
  • 18
  • You are not executing axios part from the nodejs/server side, are you? – ibrahim tanyalcin Feb 03 '22 at 09:44
  • axios is from the front end, while in the back end there is a an app.post and app.get , – Firas SCMP Feb 03 '22 at 10:08
  • the problem is that the request with postman works perfectly and returns a jwt token but performing the requests from the front end doesn't work ,there's just no cookies returned to the front-end – Firas SCMP Feb 03 '22 at 10:09

1 Answers1

0

Are you sure that no cookies are set? How are you checking that? Does the response contain the Set-Cookie header? What cookie parameters are you using (secure, same-site?). Remember that cookies in a browser are saved under the domain which set the cookie. If you're checking in the Application tab of developer tools, then you have to open the developer tools on http://192.168.0.141:3001 not on http://localhost:3000. In your SPA's Application tab you won't see those cookies, but the browser should send them with any XHR request, so you should see them in the request's Cookie header in the Network tab.

Michal Trojanowski
  • 10,641
  • 2
  • 22
  • 41