React.js + Express on Node.js: What is the correct cookie setting for cross-site requests?

247 Views Asked by At

I just want to share cookie setup for cross site requests (FE hosted on Firebase, BE hosted on Heroku) that I wasn't able to find anywhere, just a piece of info there and a piece of info somewhere else.

The setup is as follows:

React.js (Firebase) - fetch requests to the backend Node.js + Express (Heroku). Using cookie-session and cors. Please see the answer below. Hope it helps save your time.

1

There are 1 best solutions below

0
On

This is what has worked for me:

const cookieSession = require("cookie-session");
const cookieParser = require("cookie-parser");
const cors = require("cors");

// Set session cookies
  app.set("trust proxy", 1);
  app.use(
    cookieSession({
      name: "session",
      keys: [process.env.COOKIE_KEY],
      maxAge: 86400000,
      sameSite: "none",
      secure: process.env.NODE_ENV === "production",
    })
  );

app.use(cookieParser());

// Set up cors
app.use(
  cors({
    origin: process.env.CLIENT_PATH,
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    credentials: true,
  })
);

Fetch request from React:

fetch(url,
      {
        method: "GET",
        credentials: "include",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          "Access-Control-Allow-Credentials": true,
        },
      }
    );