0

I'm trying to set a cookie in the express framework, but it isn't going through, and for the life of me I can't figure out why. The relevant code looks like this:


    module.exports = function(app) {
      return function(req, res, next) {
        if (req.cookies.user_token) {
          req.session.cookie.httpOnly = false
          res.cookie('user_token', req.cookies.user_token, { domain: 'www.example.com', httpOnly: false, path: '/', maxAge: 900000 });
        }
        return res.redirect('https://www.example.com/index.jsp?other_stuff=value');
      }
    }

I can see the request going out, and that cookie is NOT getting set. I've stepped through with a debugger, and I know for certain that code is getting hit.

I found this question:

How to set cookie in node js using express framework?

Based on that, I tried calling var express = require('express'); app.use(express.cookieParser()); earlier in the code, but it didn't seem to make any difference.

Anybody have any ideas where I'm going wrong here?

Community
  • 1
  • 1
BlairHippo
  • 9,502
  • 10
  • 54
  • 78
  • Since `if (req.cookies.user_token) {` wraps the code that sets the cookie, it looks like you are checking that the cookie exists before setting it. So it never gets created. – Trott May 29 '15 at 15:04
  • @Trott: Nope. I'm looking to see if that cookie exists for the page I'm already on; if it does, I want it recreated for the page I'm going to. I'm 100% certain res.cookie is getting called; I'm stepping through it with a debugger. – BlairHippo May 29 '15 at 15:16
  • 1
    And the page you are redirecting to is in the same domain as the page that is setting the cookie? – Trott May 29 '15 at 15:42
  • @Trott: ... and that's almost certainly the problem. I didn't think that mattered, but as that redirect is actually sent back to the browser and not handled by the server, it most certainly does. Argh. – BlairHippo May 29 '15 at 19:19

1 Answers1

1

If the redirected domain (say, www.example.com) is (as indicated in the comments) different from the domain that is trying to set the cookie (say, www.foo.io), then the cookie will not be honored by the browser.

Trott
  • 66,479
  • 23
  • 173
  • 212