How can I set a cookie that is not removed when the browser is closed?
The docs of res.cookie show option parameters you can pass to the method but I haven't been able to find a configuration that makes the cookie persist after closing the browser.
res.cookie('name', 'spence', { expires: 0 });
Simply set the expires parameter to some value in the future and the cookie will persist. I was getting hung up in the docs because what I thought I wanted was a "session cookie" but like its name implies, a session cookie only lasts for the duration of the browser session.
While it isn't possible to have a cookie to persist indefinitely, you can essentially do the same thing by setting the cookie to expire on some date far in the future.
var farFuture = new Date(new Date().getTime() + (1000*60*60*24*365*10)); // ~10y
res.cookie('name', 'spence', { expires: farFuture });
Related
I want to expire session when the browser is closed.
I'm using res.cookie('testlocale', 'en', { maxAge: 900000, httpOnly: true });
Also which event should i use in front end(onbeforeunload or onunlod)
I'm not able to understand how to do this. I'm using handlebars in front-end
If you use express-session.
You can set expires: false.
req.session.cookie
Each session has a unique cookie object accompany it. This allows you to alter the session cookie per visitor. For example we can set req.session.cookie.expires to false to enable the cookie to remain for only the duration of the user-agent.
From docs
If you want to manually delete cookies on frontend, I think both are good fit. But I'm not sure it's good idea.
I have an Express 4.x app, and I pass a cookie to the browser with
res.cookie('foo','bar1', {maxAge:99999999999});
it expires in the distant future. However, 5 minutes later, I get another request from the same user, and I want to give them a new cookie.
res.cookie('foo','bar2', {maxAge:99999999999});
From my debugging, it looks like the new cookie doesn't overwrite the old cookie? Is that the case? How can I update/overwrite the old cookie with the new one?
I am about 99% certain that using the {overwrite: true} property will do the trick - from here:
https://www.npmjs.com/package/cookies
it says:
cookies.set( name, [ value ], [ options ] ) This sets the given cookie
in the response and returns the current context to allow chaining.
If the value is omitted, an outbound header with an expired date is
used to delete the cookie.
If the options object is provided, it will be used to generate the
outbound cookie header as follows:
maxAge: a number representing the milliseconds from Date.now() for
expiry expires: a Date object indicating the cookie's expiration date
(expires at the end of session by default). ... overwrite: a boolean
indicating whether to overwrite previously set cookies of the same
name (false by default). If this is true, all cookies set during the
same request with the same name (regardless of path or domain) are
filtered out of the Set-Cookie header when setting this cookie.
So that would be, in Node.js Express parlance:
res.cookie('cdt_app_token', encoded, {maxAge: 90000000, httpOnly: true, secure: false, overwrite: true});
Note that if you are using a non SSL or non TLS connection, cookies may not work if secure is true.
I have two APIs. When i hit first API from Atom, i am setting a parameter in session which is successful. But when i hit second API and trying to get session by req.session, it creates a new session instead of giving previous session. Ho do get session and parameter i set in first API into second API.
Below is my first API code in which i am setting session parameter.
function firstAPI(req, res) {////This is POST API
session = req.session;
////Doing something with req
session.message="my message";
sails.log.info("session " + JSON.stringify(session));
res.send(""session is set);
}
In terminal i am getting following session
session {"cookie":{"originalMaxAge":180000,"expires":"2017-02-28T05:03:25.304Z","httpOnly":true,"path":"/"},"message":"my message"}
Below is my second API code in which i am trying to retrieve session.
function secondAPI(req, res) {
sails.log.info("session= " + JSON.stringify(req.session));
}
Log for second API is
session= {"cookie":{"originalMaxAge":180000,"expires":"2017-02-28T05:04:18.623Z","httpOnly":true,"path":"/"}}
Following is my config/session.js file
module.exports.session = {
secret: '123abc',
cookie: {
maxAge: 3 * 60 * 1000,
},
adapter: 'redis',
host: 'localhost',
port: 6379,
db: 0,
prefix: 'sess:',
}
You can see i have set cookie time 3 mins. and in between i hit the second API. Anyone find any mistake in this?
Second request must send the cookie set by first request (in Cookie header) in order to retrieve the session.
Browsers as a client sends cookie set for the domain, by default. Other clients like cURL need to be specified. If you specifically want to use Atom check whether/how it supports to send cookie.
See Cookies & sessions:
Sessions are server-side files that contain user information, while Cookies are client-side files that contain user information. Sessions have a unique identifier that maps them to specific users. This identifier can be passed in the URL or saved into a session cookie.
Most modern sites use the second approach, saving the identifier in a Cookie instead of passing it in a URL (which poses a security risk). You are probably using this approach without knowing it
I am using Express4 to develop a web app(a simple twitter).
I use npm package "express-session" to manage session and cookie.
But I did not set cookie.maxAge. Based on the git document we have:
By default cookie.maxAge is null, meaning no "expires" parameter is set so the cookie becomes a browser-session cookie. When the user closes the browser the cookie (and session) will be removed.
but actually, when I close my chrome and start it again, I still have the same cookie generated by server in last request.
Has anyone faced same problem? Thanks for help.
You can try:
// This user should log in again after restarting the browser
req.session.cookie.expires = false;
Each session has a unique cookie object accompany it. This allows
you to alter the session cookie per visitor. For example we can
set req.session.cookie.expires to false to enable the cookie
to remain for only the duration of the user-agent.
Everything I can find on Express Sessions expiring times is about setting the cookie.
session.cookie.expires = null; // Browser session cookie
session.cookie.expires = 7 * 24 * 3600 * 1000; // Week long cookie
But the expire date of cookies is not 'secured' with your secret, as these are just cookie settings your browser manages.
How can I set the expire date of the session in the session store? Because theoretically, when someone uses your computer, they can 'fix' the expiration time of an expired cookie and continue the session, if the server side session isn't also expired at the same time as the cookie.
I can't find anything about how this works or how to set/change this.
With the Session middleware, only the encrypted session ID is stored in the client side cookie. The expired date is stored as req.session.cookie.expires in the server side store. So we can add a custom middle to check whether current session is expired.
// ...
app.use(express.cookieParser());
app.use(express.session({secret:'yoursecret', cookie:{maxAge:6000}}));
app.use(function(req, res, next) {
// if now() is after `req.session.cookie.expires`
// regenerate the session
next();
});
// ...
I wrote the solution today as the project needed that.
Here it is:
https://github.com/expressjs/session/issues/173
There are instructions there.