Express cookie-session not creating cookie on client side

1.5k views Asked by At

I have a simple ExpressJS app that is using cookie-session to create a cookie. I have a few routes defined but none are returning a cookie. The documentation for cookie-session says that req.session needs to be altered to set the cookie, which is what I'm doing, but it's not working. I'm not seeing any cookie in when I inspect the Application cookies in Chrome. My app looks like this:

const express = require('express');

const cookieSession = require('cookie-session');
const { v4: uuid } = require('uuid')

const app = express();

app.use(express.json())

app.use(cookieSession({
  name: 'shortlinks',
  keys: [process.env.SESHSECRET],
  maxAge: 30 * 24 * 60 * 60 * 1000 // 30 days
}))


app.use(function(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  req.session.id = (req.session.id || uuid());
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', '*');
  next();
})

app.get(
  '/api/links',
  (req, res, next)=> {
    res.json(readDb());
    next();
  }
)

What do I have to do to have the cookie created?

1

There are 1 answers

1
mendidou On

i hade the same probleme , and i used 'cookies' library i worked well for me... https://www.npmjs.com/package/cookies

1.npm uninstall cookie-session //for deleting the old one

2.npm install cookies //install cookies and then use it like that

const Cookie = require('cookies')

//inside your route set the token
   const cookie = new Cookie(req ,res ,{})
  cookie.set('token',accessToken{signed:false,secure:false,httpOnly:true})
//get the token back
    const token = cookie.get('token',{signed:false})
console.log(token)