Search code examples
node.jsreactjsexpresscookiessession-cookies

Express-Session Cookie not recognized by ReactJS cookie Library


I am trying to see all of my browser cookies, but I noticed that connect.sid which is created by express-session is not being recognized by the various React cookie libraries that I have tried and I'm wondering why that might be? Is this somehow distinctly different than other cookies that are set? Am I missing something?

Here is how I am setting the server on the express side:

const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const flash = require('connect-flash')
const routes = require('./controllers/routes')
// Passport
const passport = require('passport')

// Session Management
const session = require('express-session')
const redis = require('redis');
const RedisStore = require('connect-redis')(session);
const redisClient = redis.createClient({
    host: process.env.REDIS_HOST || 'localhost',
    port: process.env.REDIS_PORT || '6379',
    url: process.env.REDIS_URL || ''
});

redisClient.on_connect("error", function(error){
    console.error(error);
})

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
    
app.prepare()
.then(() => {
  const server = express()

  // Setting proxy for session handlng that is required for non-dev servers
  if (!dev){
      server.set('trust poxy', 1)
  }

  console.log(process.env.DB_DATABASE)
  
  // Session Management
  server.use(session({
      store: new RedisStore({ client: redisClient }),
      secret: process.env.SESSION_SECRET,
      saveUninitialized: false,
      resave: false,
      cookie: {
          secure: process.env.SESSION_SECURE || false,
          httpOnly: true,
      }
  }))

  // Request notifications. Must be used prior to routes
  server.use(flash());

  // Passport middleware
  server.use(passport.initialize())
  server.use(passport.session())
//   Form body parsing
  server.use(bodyParser.json())
  server.use(bodyParser.urlencoded({extended: true}))
  
//   server.use(helmet()) Enable at later date

// ExpressJS Routes
  server.use(routes);

    // mount the router on the app 
    // Any routes that aren't handled by ExpressJS are handled by NextJS
  server.get('*', (req, res) => {
    return handle(req, res)
  })
    
  server.listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})
.catch((ex) => {
  console.error(ex.stack)
  process.exit(1)
})

Here is how I am trying to access the browser cookies (Attempted with nookies and js-cookie) on the React front-end:

import {parseCookies} from 'nookies'
import Cookies from 'js-cookie'

const AppSession = ({ children }) => {

        console.log(parseCookies())
        console.log(Cookies.get())
        console.log(Cookie.get())
}

export default AppSession;

Here is what is logged:

{_ga: "GA1.1.630490776.1602939000"}
{_ga: "GA1.1.630490776.1602939000"}

Here are my browser cookies:

cookies


Solution

  • You set the connect.sid session cookie with the httpOnly attribute. See Restrict access to cookies

    A cookie with the HttpOnly attribute is inaccessible to the JavaScript Document.cookie API; it is sent only to the server. For example, cookies that persist server-side sessions don't need to be available to JavaScript and should have the HttpOnly attribute. This precaution helps mitigate cross-site scripting (XSS) attacks.

    That's why you can't get or set it using js-cookie package in the browser.