Search code examples
node.jsexpresssession-cookiessingle-page-applicationprogressive-web-apps

How do I use session and cookies for express.use(express.static('static'))?


I have a question about session cookies over web from express backend. In the front I am using a Vue PWA/SPA that is being mounted on express static via express.use(express.static('static')); to serve the built files.

I did some research that we can attach options to the function with

express.use(cookieParser());
express.use(session({
  secret : `${uuid()}`,
  proxy: true,
  resave: false,
  saveUninitialized: false,
  cookie: {
    maxAge: 1000 * 60 * 30
  }
}))

const options = {
  dotfiles: 'ignore',
  etag: false,
  extensions: ['html', 'htm'],
  index: false,
  maxAge: '1d',
  redirect: false,
  setHeaders: function(res, path, stat) {
    res.set('Set-Cookie', "myCookie=cookieValue;Path=/");
    res.set('x-timestamp', Date.now());
  }
}
express.use(express.static('static' , options));

After doing those, hoping I can read myCookie=cookieValue on the browser via document.cookie but I don't see those datra being printed on the page.

I have also tried it with __dirname method as well and then do

app.get("/", function(req, res) {
  req.session.fullname = "Oh mi gee";
  res.render("index");
});

didn't give me what I want. Is there a way for me to add session/cookies so I can somewhat secure the API calls by passing cookie data on the header for confirmation?

Thanks in advance!


Solution

  • I have figured it out, is to place this express.static at the very end of the express configuration.

    before we establish express.static we will want to do

    app.use('/path', (req, res, next) => {
      req.session.views++;
      res.cookie('myCookie', 'cookieValue', {
        maxAge: 1000 * 60 * 30
      });
      console.log(req.session);
      next();
    })
    

    will transfer the cookies to the client side with the expiry of half an hour.