Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Express JS set a cookie doesn't work when using res.json

I have a login route where I want to set a cookie after I verify the login credentials. The client and the server are on different ports.

const app = express();

app.use(
  cors({
    credentials: true,
    origin: true,
  })
);
app.use(cookieParser());

app.use('/login', (req, res) => {

  res.cookie('secureCookie', JSON.stringify({ id: 1 }), {
    secure: false,
    httpOnly: true,
  });

  return res.json({ success: true });
});

app.use('/check', (req, res) => {
  console.log(req.cookies);

  return res.json({ id: 1 });
});

The issue is that I don’t see the cookie in the devtools (applications tab) after the login request returns. Also, when trying to fetch the check endpoint using credentials: 'include' it doesn’t send the cookie.

What I’m doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here are the requests:

  fetch('http://localhost:4000/login');

  fetch('http://localhost:4000/check', {
    credentials: 'include',
  });

>Solution :

According to Using Fetch article on mdn

Unless fetch() is called with the credentials option set to include, fetch():

  • won’t send cookies in cross-origin requests
  • won’t set any cookies sent back in cross-origin responses

credentials: include must be set for requests to make them save cookies

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading