0

I have an express application that works with session cookies (express-session).

I want to make the app cookieless and use a custom header instead of a cookie header.

the idea is to make a middleware that intercepts the request and get the session id from a header (eg. X-SESSION-ID) and set the value into req.sessionID

app.use((req, res, next) => {
  // read the session ID from header and set sessionID
  const sid = req.header('x-session-id');
  if (sid) {
    req.sessionID = sid;
  }
  next();
});

but i need another middleware logic for intercept the response (before it is send), retrieve the session cookie and set the value into the header, this is my try:

app.use((req, res, next) => {
  // read the session ID from header and set sessionID
  const sid = req.header('x-session-id');
  if (sid) {
    req.sessionID = sid;
  }
  next();
});

// init the session
app.get('/api/login', (req, res, next) => {
   req.session.store = {
       username: 'foo'
   }; 
   req.session.save();
   res.send({result: true})
});

app.use((req, res, next) => {
  // read the session ID from the cookie and set the header
  const sid = res.cookie['session-id'];
  if (sid) {
    res.header('x-session-id', sid);
    delete res.cookie['session-id']; // delete the cookie from response
  }
  next();
});

but the last middleware is never called...

How intercept the response and remove the session cookie to put the value into a header?

ar099968
  • 5,717
  • 7
  • 51
  • 110
  • 1
    Does this answer your question? [express.js - how to intercept response.send() / response.json()](https://stackoverflow.com/questions/33732509/express-js-how-to-intercept-response-send-response-json) – stdob-- Dec 21 '21 at 16:15

0 Answers0