Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Client-Side Accessible Cookie In Express

I'm working on a Node app that uses Express and SocketIO. I want to set a cookie in my Express controller which is then accessible from my client-side Javascript code. Everything that I try doesn't seem to work:

res.setHeader('Set-Cookie','test=value'); res.cookie('rememberme', 'yes', { maxAge: 900000 }); 

Is there something I'm missing here? Thanks in advance!

like image 250
dshipper Avatar asked Jun 10 '12 06:06

dshipper


People also ask

Can I set cookie on client side?

There is no difference. A regular cookie can be set server side or client side. The 'classic' cookie will be sent back with each request. A cookie that is set by the server, will be sent to the client in a response.

How do I send cookies to client Express?

In order to correctly set cookies accessible on the client just use a snippet like the following: res. cookie('rememberme', 'yes', { maxAge: 900000, httpOnly: false}); I've also noticed that if you call this command and then call res.

How do you set an Express session cookie?

var cookieSession = require('cookie-session') var express = require('express') var app = express() app. use(cookieSession({ name: 'session', keys: ['key1', 'key2'] })) // Update a value in the cookie so that the set-cookie will be sent. // Only changes every minute so that it's not sent with every request. app.

Is cookie server side or client side?

Cookies are client-side files that are stored on a local computer and contain user information. Sessions are server-side files that store user information. Cookies expire after the user specified lifetime. The session ends when the user closes the browser or logs out of the program.


1 Answers

Figured it out! By default Express sets the option httpOnly to true. This means that your cookies cannot be accessed by the client-side Javascript. In order to correctly set cookies accessible on the client just use a snippet like the following:

res.cookie('rememberme', 'yes', { maxAge: 900000, httpOnly: false}); 

I've also noticed that if you call this command and then call res.redirect, the cookie won't get set. This command needs to be followed by res.render at some point in order for it to work. Not sure why this is.

like image 146
dshipper Avatar answered Sep 22 '22 18:09

dshipper