How can I set cookie in node js using express framework?
Asked Answered
P

9

277

In my application, I need to set a cookie using the express framework. I have tried the following code but it's not setting the cookie.

var express = require('express'), http = require('http');
var app = express();
app.configure(function(){
      app.use(express.cookieParser());
      app.use(express.static(__dirname + '/public'));

      app.use(function (req, res) {
           var randomNumber=Math.random().toString();
           randomNumber=randomNumber.substring(2,randomNumber.length);
           res.cookie('cokkieName',randomNumber, { maxAge: 900000, httpOnly: true })

           console.log('cookie have created successfully');
      });

});

var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(5555);
Paramedical answered 25/4, 2013 at 7:48 Comment(4)
How are you verifying that the cookie is not set? Have you checked the response headers the browser is getting?Michail
@Michail i have added log statement.if it set means it will display as 'cookie have created susccessfully'..Paramedical
ok, then either your middleware is not invoked, or some of the previous statements give an exception.Michail
if i removed 'app.use(express.static(__dirname + '/public'));' this line means it's set the cookieParamedical
P
343

The order in which you use middleware in Express matters: middleware declared earlier will get called first, and if it can handle a request, any middleware declared later will not get called.

If express.static is handling the request, you need to move your middleware up:

// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());

// set a cookie
app.use(function (req, res, next) {
  // check if client sent cookie
  var cookie = req.cookies.cookieName;
  if (cookie === undefined) {
    // no: set a new cookie
    var randomNumber=Math.random().toString();
    randomNumber=randomNumber.substring(2,randomNumber.length);
    res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
    console.log('cookie created successfully');
  } else {
    // yes, cookie was already present 
    console.log('cookie exists', cookie);
  } 
  next(); // <-- important!
});

// let static middleware do its job
app.use(express.static(__dirname + '/public'));

Also, middleware needs to either end a request (by sending back a response), or pass the request to the next middleware. In this case, I've done the latter by calling next() when the cookie has been set.

Update

As of now the cookie parser is a seperate npm package, so instead of using

app.use(express.cookieParser());

you need to install it separately using npm i cookie-parser and then use it as:

const cookieParser = require('cookie-parser');
app.use(cookieParser());
Pentagram answered 25/4, 2013 at 8:9 Comment(11)
also i have one more question how can i check whether the cokkie is existing or not before setting the cookieParamedical
I edited my answer to show you how to check if the cookie is already set.Pentagram
now its working fine but i'm getting the log 8 times.it means that same code is running 8 times. cookie exists 7885156760457903 cookie exists 7885156760457903 cookie exists 7885156760457903 cookie exists 7885156760457903 cookie exists 7885156760457903 cookie exists 7885156760457903 cookie exists 7885156760457903Paramedical
You probably have some JS and/or CSS files on your page. Those will be handled by express.static, which will handle them after your middleware. So for each JS or CSS file, the code will be called.Pentagram
yes u r correct i have css and js files...how to resolve this one.Paramedical
Well, what's the problem exactly?Pentagram
setting cookie value is executing 8 times.i don't know how to resolve this.Paramedical
It doesn't set the cookie 8 times, it says the cookie already exists. Which is to be expected.Pentagram
Note that cookie parser should now be installed separately. See npmjs.com/package/cookie-parserBelayneh
Error: Most middleware (like cookieParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.Splendiferous
Good ;) Just wanted to let you know. Thanks for updating.Splendiferous
J
210

Set Cookie?

res.cookie('cookieName', 'cookieValue')

Read Cookie?

req.cookies

Demo

const express('express')
    , cookieParser = require('cookie-parser'); // in order to read cookie sent from client

app.get('/', (req,res)=>{

    // read cookies
    console.log(req.cookies) 

    let options = {
        maxAge: 1000 * 60 * 15, // would expire after 15 minutes
        httpOnly: true, // The cookie only accessible by the web server
        signed: true // Indicates if the cookie should be signed
    }

    // Set cookie
    res.cookie('cookieName', 'cookieValue', options) // options is optional
    res.send('')

})
Jehial answered 19/10, 2016 at 14:59 Comment(5)
hi, could you say what is signed: true?Asphodel
if you have advised to set cookie as sign, it's important to note that req.cookie will return empty. You can only retrieve signed cookie from req.signedCookiesChemush
You need to add this as well: const app = express() app.use(cookieParser())Enormous
@Wayne Chiu this was not working with Safari browser, can you please help me for thisFontanel
is there a way to set the cookie without having to use res.cookie?Macaronic
F
64

Not exactly answering your question, but I came across your question, while looking for an answer to an issue that I had. Maybe it will help somebody else.

My issue was that cookies were set in server response, but were not saved by the browser.

The server response came back with cookies set:

Set-Cookie:my_cookie=HelloWorld; Path=/; Expires=Wed, 15 Mar 2017 15:59:59 GMT 

This is how I solved it.

I used fetch in the client-side code. If you do not specify credentials: 'include' in the fetch options, cookies are neither sent to server nor saved by the browser, even though the server response sets cookies.

Example:

var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');

return fetch('/your/server_endpoint', {
    method: 'POST',
    mode: 'same-origin',
    redirect: 'follow',
    credentials: 'include', // Don't forget to specify this if you need cookies
    headers: headers,
    body: JSON.stringify({
        first_name: 'John',
        last_name: 'Doe'
    })
})
Fluxion answered 11/3, 2017 at 12:16 Comment(2)
I have inspected my post request in browser but this field is not going with the post request?Conspectus
If using XHR or Jquery, use 'withCredentials: true' insteadDextran
A
34

Set a cookie:

res.cookie('cookie', 'monster')

https://expressjs.com/en/4x/api.html#res.cookie


Read a cookie:
(using cookie-parser middleware)

req.cookies['cookie']

https://expressjs.com/en/4x/api.html#req.cookies

Alina answered 3/7, 2017 at 22:0 Comment(0)
A
19

Setting cookie in the express is easy

  1. first install cookie-parser
npm install cookie-parser
  1. using middleware
const cookieParser = require('cookie-parser');
app.use(cookieParser());
  1. Set cookie know more
res.cookie('cookieName', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })
  1. Accessing that cookie know more
console.dir(req.cookies.cookieName)

Done!

Accessary answered 10/2, 2021 at 23:16 Comment(0)
S
8
  1. setting a cookie can be done as such:

    res.cookie('cookie name', 'cookie value', [options])
    

where cookie_name is the name(String) of the cookie you wish to set, for example - "token", and the cookie value is the value(String) you wish to store in the said cookie. as far as options go, you can read more about them here: https://expressjs.com/en/api.html

one example of an option is 'maxAge' which indicates how long a cookie is valid, this is used for example when assigning an authentication token and you wish to limit the time a user can stay logged in before having to re-login.

  1. Reading a cookie can be done as such:

     req.cookies['cookie name']
    

which will return the value of the cookie.

Stereoisomerism answered 6/4, 2022 at 18:58 Comment(1)
This works only if 'cookie-parser' package is installed and added as a middleware.Organ
A
5

If you have a problem with setting multiple cookies for one request

Try this way:

res.setHeader('Set-Cookie', [
    `accessToken=${accessToken}; HttpOnly; Path=/; Max-Age=${60 * 60}; Secure=True;`,
    `refreshToken=${refreshToken}; HttpOnly; Path=/; Max-Age=${60 * 60 * 24 * 7 * 2}; Secure=True;`
]);
Adversity answered 9/11, 2022 at 1:55 Comment(0)
A
2

Isomorphic Read cookie helper:

function getCookieValue(cookieName = '', cookie = '') {
  const matches = cookie.match(`(^|[^;]+)\\s*${cookieName}\\s*=\\s*([^;]+)`)
  return matches ? matches.pop() : ''
}

// Node with express:
getCookieValue('cookieName', req.headers.cookie)

// Browser:
getCookieValue('cookieName', document.cookie)

Write in Node with express:

res.cookie('cookieName', 'cookieValue')

Write in the browser:

function setCookie(
  cname,
  cvalue,
  exdays = 100 * 365 /* 100 days */
) {
  const now = new Date()
  const expireMs = exdays * 24 * 60 * 60 * 1000
  now.setTime(now.getTime() + expireMs)

  document.cookie = `${cname}=${cvalue};expires=${now.toUTCString()};path=/`
}

// Example of usage
setCookie('cookieName', 'cookieValue')
Aquamarine answered 1/2, 2022 at 9:54 Comment(1)
res.cookie wasn't working somehow in my POST request. Probably because I'm sending JSON strings back, not using res.send. Handling it client-side in JavaScript before issuing the request was a quick hack that worked for me (in this specific case). Thanks!Annuity
L
1

I think this might help you. I got the same problem while sending request from axios and show error about credentials and something like that. For that you have to use cors() in the backend with corsoptions as

npm i cors;

after cors has been successfully installed. Import in main server.js file

const cors = require('cors');

and after that use cors middleware before routing . In express it matters where you put the middleware. so put cors at above of routing.

var corsoption={
origin:"http://localhost:3000", //origin from where you requesting
credentials:true
}
//using cors
app.use(cors(corsoption));

only after setting these options send cookie as response it will set cookie on browser correctly and allow cross origin with credentials. NOTE: IF YOU WANT TO PARSE COOKIE ON BACKEND WE NEED TO INSTALL

Cookie-parser

to parse the cookie from browser request.

Lascivious answered 9/3, 2023 at 9:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.