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
  • 169
  • 10
  • 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

2 Answers2

0

You did not mention if you used cookie-parser; to use cookies in express you need to install cookie-parser and use it as follows:

npm install cookie-parser;

Then in your app;

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

// when adding middlewares

app.use(cookieParser())
Abiola
  • 43
  • 1
  • 5
  • yes sure I used it , my bad I didn't mention it – Firas SCMP Feb 03 '22 at 09:25
  • Then you need to set up your server to accept and set cookies for cross-origin requests: ```app.use(function(req, res, next) { res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Origin', req.headers.origin); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'); next(); });``` see: https://stackoverflow.com/questions/29250894/cookie-not-set-on-cross-domain-angularjs-and-nodejs-express – Abiola Feb 03 '22 at 10:59
  • I tried so, but still the front end in the browser doesn't recieve any jwt token :( – Firas SCMP Feb 03 '22 at 11:03
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 03 '22 at 11:08
  • I probably need to see more code to know what might be wrong with this. Where do you set the cookies on the server, from this middleware, any request that does not have an access-token cookie will respond with a 400 status without further processing. How do you set the cookie for a user the first time? – Abiola Feb 03 '22 at 11:43
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
  • 7,150
  • 2
  • 16
  • 32