0

A node express api for SPA with the following:

const express = require ('express');
const bodyParser = require ('body-parser');
const cookieSession = require ('cookie-session');
const cors = require ('cors');  

const app = express();
app.use (cors());

app.use (cookieSession({
  name: 'app',
  keys: ['a-key'],

  maxAge: 7 * 24 * 3600 * 1000, // 7 days
}));

const router = express.Router();
app.use ('/api', router);

router.use ('/login', login);
router.use ('/logout', logout);
router.use ('/users', users);
etc ...

app.listen (port);

Requests from the SPA are made using fetch:

try {
  await fetch ('/api/users');
  ... etc
}

Express runs on localhost:3000 at the mo´, the dev SPA on localhost:5000.

A cookie is not being set in the browser; and console.log of req.session shows an empty {} object.

I have tried:

credentials: true,
origin: 'http://localhost:5000'

in the cors initiation

I have also tried:

secure: false,
httpOnly: false,
sameSite: false

in the cookieSession initiation

I have also tried including:

credentials: 'include'

on the fetch requests

None of this has worked, either alone, or all together.

What gives?

minisaurus
  • 1,099
  • 4
  • 17
  • 30

1 Answers1

0

It appears that the

fetch (url, {
  credentials: 'include'
});

in the SPA is in fact needed, and once I had logged out and in again, the session was set correctly in the browser.

minisaurus
  • 1,099
  • 4
  • 17
  • 30