nodejs – using express-session

In this article I will show you how to use express sessions. Default express-sessions are stored in memory. With help of the package ‘session-file-store’ you can persist sessions to your filesystem.

Use memory store for sessions (default)

First setup your nodejs app to use express and express-essions:

# Create new package.json file
npm init -y
# Add express and express-ession to node module
npm install express express-ession --save

Now add an app.js file to the current folder with the following contents:

const session = require('express-session');
// const FileStore = require('session-file-store')(session);
const express = require('express')
const app = express()
const port = 3000

        secret: 'mysecret', 
        resave : false, 
        saveUninitialized : false,
        // store: new FileStore()

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

    if (req.session.views) {
        res.send(`Returning client (${req.session.views} times})`)
    else {
        req.session.views = 1
        res.send('New client')

app.get('/destroy', (req, res) => {
    res.send('Session destroyed')

app.listen(port, () => console.log(`Listening on port ${port}`))

Start your nodejs application with

nodemon app.js

and navigate to ‘http://localhost:3000/’. A webpage shows up with the text ‘New client’. Now hit F5 and see the text ‘Returning client (2 times)’ appearing. The session is created on first request with a ‘views’ variable in it. Every next visit of the site this ‘views’ variable is incremented with 1.

Use a FileStore for session data

Now if you want to use persistent session you will have to install the session-file-store with:

npm install session-file-store --save

Uncomment the two lines of code in app.js and you are ready to go. Sessions are stored on the filesystem in a sub folder called ‘sessions’ below the location of your app.js.

If you are using nodemon to monitor changes in your nodejs code be sure to exclude monitoring of the ‘sessions’ folder as it will change on every request of the browser. Start nodemon with:

nodemon --ignore sessions/ app,js

Custom session id’s

In case you want to generate custom session id’s you will have to provide a genid callback to the session initialized. First add the uuid package with

npm install uuid

Add the require statement to the top of your app.js file:

const uuidv1 = require('uuid/v1')

And add the genid callback to the session initialization:

        genid: (req) => {
            return 'app_' + uuidv1() // use UUIDs for session IDs
        secret: 'keyboard cat', 
        resave : false, 
        saveUninitialized : false,
        store: new FileStore()

Leave a Reply

Your email address will not be published. Required fields are marked *