Another very common use of Express middleware is to provide session support for applications. For complex session management, you might want to implement it yourself, but for basic session support, the cookie-session
middleware works relatively well.
The cookie-session
middleware utilizes the cookie-parser
middleware underneath, so you need to add cookie-parser
prior to adding cookie-session
. The following shows the syntax for adding the cookie-session
middleware:
res.cookie([options])
The options
parameter allows you to set the following properties for the cookie:
key: The name of the cookie that identifies the session.
secret: A string that is used to sign the session cookie to prevent cookie tampering.
cookie: An object that defines the cookie’s settings, including maxAge
, path
, httpOnly
, and signed
. The default is {path:'/', httpOnly:true, maxAge:null }
.
proxy: A Boolean that, when true
, causes Express to trust the reverse proxy when setting secure cookies via x-forwarded-proto
.
When cookie-session
is implemented, a session is stored as an object in req.session
. Any changes you make to req.session
flow across multiple requests from the same browser.
Listing 19.6 shows an example of implementing a basic cookie-session
session. Notice that cookie-parser
is added first in line 5 and then cookie-session
is added in line 6, with a secret
string. There are two routes in this example. When the /restricted
route is accessed, the restrictedCount
value is incremented in the session, and the response is redirected to /library
. Then in library
, if restrictedCount
is not undefined
, the value is displayed; otherwise, a welcome message is displayed. Figure 19.3 shows the different outputs in a web browser.
01 var express = require('express'),
02 var cookieParser = require('cookie-parser'),
03 var cookieSession = require('cookie-session'),
04 var app = express();
05 app.use(cookieParser());
06 app.use(cookieSession({secret: 'MAGICALEXPRESSKEY'}));
07 app.get('/library', function(req, res) {
08 console.log(req.cookies);
09 if(req.session.restricted) {
10 res.send('You have been in the restricted section ' +
11 req.session.restrictedCount + ' times.'),
12 }else {
13 res.send('Welcome to the library.'),
14 }
15 });
16 app.get('/restricted', function(req, res) {
17 req.session.restricted = true;
18 if(!req.session.restrictedCount){
19 req.session.restrictedCount = 1;
20 } else {
21 req.session.restrictedCount += 1;
22 }
23 res.redirect('/library'),
24 });
25 app.listen(80);