req.cookies undefined express js cookie-session

892 views Asked by At

Req.cookies is undefined whilst req.headers.cookie contains the cookies, I am using cookie-session and express. I am declaring cookie-session before the routes. For refrence I grabbed my code from this article: https://medium.com/@manishsharma8301/google-oauth-using-passport-js-how-to-get-started-46a200c1fec3

Only difference is that I am using spotify oauth instead.

app.use(
    cors({
        origin: "http://localhost:8888",
        methods: "GET, HEAD, PUT, PATCH, POST, DELETE",
        credentials: true
    })
)

app.use(bodyParser.json());

app.use(cookieSession({
    name: 'session-name',
    keys: ['key1', 'key2']
}));

app.use(passport.initialize());
app.use(passport.session());

app.use('/', authRoutes);

app.listen(8888, () => console.log(`App listening on port ${8888}`));
1

There are 1 answers

0
Obsidianlab On

As per doc:

Create a new cookie session middleware with the provided options. This middleware will attach the property session to req, which provides an object representing the loaded session. This session is either a new session if no valid session was provided in the request, or a loaded session from the request.

So see if the cookie is attached to the req.session not req.cookie.

Reference :

https://www.npmjs.com/package/cookie-session#:~:text=Create%20a%20new,from%20the%20request.

An example which i got working with your code was

var cookieSession = require('cookie-session');
var express = require('express');
var cors = require('cors');
const passport = require('passport');

var app = express();

app.use(
  cors({
    origin: 'http://localhost:1000',
    methods: 'GET, HEAD, PUT, PATCH, POST, DELETE',
    credentials: true,
  })
);

app.use(
  cookieSession({
    name: 'sessiontwo',
    keys: ['key1', 'key2'],
  })
);

app.use(passport.initialize());
app.use(passport.session());

app.get('/', function (req, res, next) {
  console.log('Session', req.session);

  // Update views
  req.session.views = (req.session.views || 0) + 1;

  // Write response
  res.end(req.session.views + ' views');
});

app.listen(1000, () => console.log(`App listening on port ${1000}`));

// Result of get('/') 1 view and increments on reload