3

I'm trying to set a cookie with a specific expiry date of 3 months. I can set the cookie fine but the expiry set for it isn't working.

I've used momentJS to create a date object at the time I want. The correct time is being outputted from the console but the cookie doesn't have the right value, it's value is to expire in a couple minutes instead of the 3 months from the date.

// Create the date the cookies will expire on
var cookieDate = moment().add(6, 'months').toDate();
console.log(cookieDate);
res.cookie('username', user.username, { expires: cookieDate });

I looked through the docs and it just asks for a Date object to be passed to it.

I also looked around on stackoverflow and the only thing I could find was this which tells the OP to use req.session.cookie which just doesn't seem right as you should be setting a cookie on response to the client and not in a session.

Community
  • 1
  • 1
silverlight513
  • 5,268
  • 4
  • 26
  • 38

1 Answers1

2

I found out through some trial and error that the date object created by moment.toDate() may have been a valid Date object it wasn't accepted by Express.

The following code fixed the bug:

var cookieDate = new Date(moment().add(6, 'months').toDate());
res.cookie('username', user.username, { expires: cookieDate });
silverlight513
  • 5,268
  • 4
  • 26
  • 38