Express.Js Session explained super easy with example

CodeNerd
2 min readDec 30, 2022
Photo by Nubelson Fernandes on Unsplash

Express.js is a web application framework for Node.js, designed for building web applications and APIs. It is the de facto standard server framework for Node.js.

express-session is a middleware module in Express.js that allows you to create sessions in your web application. It stores session data on the server side, using a variety of different storage options, and allows you to track the activity of a user across requests.

Here’s an example of how you might use express-session in an Express.js app:

const express = require('express')
const session = require('express-session')

const app = express()

app.use(session({
secret: 'my-secret', // a secret string used to sign the session ID cookie
resave: false, // don't save session if unmodified
saveUninitialized: false // don't create session until something stored
}))

app.get('/', (req, res) => {
if (req.session.views) {
req.session.views++
res.setHeader('Content-Type', 'text/html')
res.write('<p>views: ' + req.session.views + '</p>')
res.write('<p>expires in: ' + (req.session.cookie.maxAge / 1000) + 's</p>')
res.end()
} else {
req.session.views = 1
res.end('welcome to the session demo. refresh!')
}
})

app.listen(3000)

--

--

CodeNerd

A lifelong learner and passionate about all things code. From building websites to creating software applications, I love bringing ideas to life through coding.