Search code examples
reactjsexpressexpress-session

Accessing express session cookies in react


Is there any way to just access the cookies generated from express-session in react? I have generated an express-session cookie as follows

app.use(
session({
  key: "userId",
  secret: "subscribe",
  resave: false,
  saveUninitialized: false,
  cookie: {
    expires: 60 * 60 * 24,
  },
}) );

Now if I'm trying to access the cookies from react using universal-cookie or js-cookie libraries I cannot access the cookie.

PS: In react file I have added

Axios.defaults.withCredentials = true;

and in backend file I have configured cors as

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

but it is still not working.


Solution

  • When you use express-session, the only cookie sent to frontend is connect.sid. By default, it is httpOnly, this way you cannot access it in React. To achieve it, you need to change httpOnly config to false.

    app.use(
      session({
        key: "userId",
        secret: "subscribe",
        resave: false,
        saveUninitialized: false,
        cookie: {
          expires: 60 * 60 * 24,
          httpOnly: false,
        },
      })
    );