The cookie-parser
middleware provided in Express makes handling cookies extremely simple. The cookie-parser
middleware parses the cookies from a request and stores them in the req.cookies
property as a JavaScript object. The cookie-parser
middleware uses the following syntax:
express.cookie-parser([secret])
Note
The cookie-parser
middleware will be renamed cookie
when Connect 3.0 ships. You may need to change your code to support the new name if it doesn’t end up being backward compatible.
The optional secret
string parameter prevents cookie tampering by internally signing the cookies using the secret
string.
To set a cookie in a response, you can use the res.cookie()
method shown below:
res.cookie(name, value, [options])
A cookie with the name
and value
parameters specified is added to the response. The options
parameter allows you to set the following properties for the cookie:
maxAge: The amount of time, in milliseconds, for a cookie to live before it expires.
httpOnly: A Boolean that, when true
, indicates that this cookie should only be accessed by the server and not by client-side JavaScript.
signed: A Boolean that, when true
, indicates that the cookie will be signed, and you need to access it using the req.signedCookie
object instead of the req.cookie
object.
path: The path that the cookie applies to.
For example, the following sets a hasVisited
cookie:
res.cookie('hasVisited', '1',
{ maxAge: 60*60*1000,
httpOnly: true,
path:'/'});
You can remove cookies from a client by using the res.clearCookie()
method. For example:
res.clearCookie('hasVisited'),
Listing 19.5 shows a simple example of getting a cookie named req.cookies.hasVisited
from a request and setting it if it hasn’t already been set.
01 var express = require('express'),
02 var cookieParser = require('cookie-parser'),
03 var app = express();
04 app.use(cookieParser());
05 app.get('/', function(req, res) {
06 console.log(req.cookies);
07 if (!req.cookies.hasVisited){
08 res.cookie('hasVisited', '1',
09 { maxAge: 60*60*1000,
10 httpOnly: true,
11 path:'/'});
12 }
13 res.send("Sending Cookie");
14 });
15 app.listen(80);
18.191.236.255