In previous chapters, all of our APIs have placed no authentication requirements on the caller, nor made any attempt to link one request with any previous request. For users to have their own book bundles, we need some identifying token that persists between requests. This is a session.
Sessions are most typically implemented by giving each new user a cookie with an ID that links to some backing session data. Subsequent requests made by the user’s browser (also called a user agent) will include the cookie value, allowing the server to update the user’s session information.
In Express, this is all implemented with middleware. You’ll need the express-session and session-file-store modules. Install those with npm.
| | $ npm install --save -E express-session@1.15.6 session-file-store@1.1.2 |
The express-session module is responsible for using cookies to associate session data with requests. By default, this will store session data in memory by using a MemoryStore. That won’t work for us for two reasons—one that applies to development, and one that applies to production.
During development, nodemon will restart the server each time you save a source code file, wiping out any session data in memory. This makes it incredibly tedious to develop and test session-based code, since each time you change the code, it’ll sign you out!
In production, the express-session’s default MemoryStore is not recommended due to memory leaks and a single-processor limit. There’s no shared memory between Node.js processes.
Instead of MemoryStore, we’ll use the FileStore class from the session-file-store module during development. This session-storage implementation uses a json file per session to store data associated with each cookie.
Open your server.js file for editing and find the line that creates the Express app instance:
| | const app = express(); |
Then insert the following lines immediately below it:
| | // Setup Express sessions. |
| | const expressSession = require('express-session'); |
| | if (isDev) { |
| | // Use FileStore in development mode. |
| | const FileStore = require('session-file-store')(expressSession); |
| | app.use(expressSession({ |
| | resave: false, |
| | saveUninitialized: true, |
| | secret: 'unguessable', |
| | store: new FileStore(), |
| | })); |
| | } else { |
| | // Use RedisStore in production mode. |
| | } |
We pull in the expressSession middleware and then enter an isDev check. Using the FileStore class, the app.use call sets up the expressSession middleware with its required options. Here’s a quick rundown of each:
resave—This option indicates whether the session should be saved on each request, even if no changes have been made. Since both the FileStore we’re using now and the RedisStore that we’ll be using later implement the touch operation, we can safely set resave to false.
saveUninitialized—This dictates whether to save new but unmodified sessions. Setting this to false protects against race conditions in which the user agent makes simultaneous cookieless requests. It’s also useful if you need to get the user’s permission before using cookies. During development, it helps to set this to true so you can inspect the session data even when it’s empty.
secret—This required string is used to sign cookie values, making it harder for an attacker to guess users’ session IDs. In production mode, we’ll pull this in from nconf.
store—This is an instance of a class that extends the Store class of the express-session module. It is used to implement session data storage.
The FileStore can take a configuration object that allows you to specify various options.[89] The defaults are all fine in our case. This means that it will store session information in the ./sessions directory.
After you save this file, visit your running server at http://b4.example .com:60900. It should look the same, of course, but now there should be a sessions directory in your project folder that contains a JSON file. The file’s name matches the session ID (the cookie value), and it contains the data associated with the session. You can take a peek by feeding the file through jq.
| | $ cat sessions/*.json | jq '.' |
| | { |
| | "cookie": { |
| | "originalMaxAge": null, |
| | "expires": null, |
| | "httpOnly": true, |
| | "path": "/" |
| | }, |
| | "__lastAccess": 1499592937433 |
| | } |
The session data is pretty much empty, but at least it’s there. You can use this technique at any time to inspect your session data—it’s a valuable tool when debugging session-based problems. We’re now in position to add the sign-in flow.