So let's assume you've configured cookie-session
something like this:
var cookieSession = require('cookie-session');
app.use(cookieSession({
keys: ['secret']
}));
Then let's store some data in the session:
req.session.user_id = 123;
If you look in your browser's dev tools you'll see 2 cookies set:
express:sess = eyJ1c2VyX2lkIjoxMjN9
express:sess.sig = 01I_Rx2gACezZI1tdl2-NvxPq6w
The cookie express:sess
is base64 encoded. If we decode it we get {"user_id":123}
. It's important to appreciate that the session data is being stored in the cookie itself - this isn't just an id for the session.
The other cookie, express:sess.sig
, is the signature. This signature is generated using the key (secret
in this example) and is used to help prevent tampering. It's easy for anyone to modify express:sess
but unless they can also generate the corresponding express:sess.sig
the server will know it's been changed.
All that said, I suggest you take a look at the express-session
middleware. That also uses cookies but it only uses them to store the session id. No data is stored in the cookie, that is all stored on the server. This is much more akin to how sessions work in most other web frameworks but I can't say for certain which approach is best suited to your needs.
Whichever approach you use the cookie with be set to httponly
by default. You'll be able to verify this in your browser's dev tools. This means that it's included on HTTP requests but isn't accessible via client-side JavaScript. This is a security measure designed to make it more difficult for malicious code to steal the cookie. You can disable this security feature in cookie-session
using:
app.use(cookieSession({
httpOnly: false,
keys: ['secret']
}));
You'll then be able to access those cookies using document.cookie
.
I reiterate that this is a security measure and turning it off isn't recommended. It's impossible for me to judge whether this is a genuine concern in your application.
It isn't clear from your question whether you actually want to parse the values out of the cookie or just check for its existence. If you need to parse it then you'll need to base64 decode the relevant cookie value and then JSON decode it.
There are various alternative approaches you might adopt to keep the cookies httponly
. Without knowing more about what you're going to do with this information it's difficult to be specific. If you're using Express views (i.e. template rendering) then you can do all the work in the template. If you're in SPA territory then you could maybe use an AJAX request to gather the relevant information. At a pinch you could even use another cookie to give you the information you need while keeping the session cookies safe.
atob
) the cookie, edit that data, then re-encode it as base64 (btoa
), but would have to somehow generate the correct sig - which isn't really an option ? – Damarisdamarra