0
0
ExpressHow-ToBeginner · 4 min read

How to Use Session Authentication in Express: Simple Guide

Use the express-session middleware in Express to enable session authentication by configuring it with a secret and options. Store user login state in the session object to keep users logged in across requests.
📐

Syntax

The basic syntax to use session authentication in Express involves importing express-session, configuring it with a secret key, and adding it as middleware. You then store user data in req.session to track login state.

  • secret: A string to sign the session ID cookie.
  • resave: Forces session to be saved back to the store even if not modified.
  • saveUninitialized: Saves new sessions that are unmodified.
javascript
import express from 'express';
import session from 'express-session';

const app = express();

app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true
}));

app.get('/', (req, res) => {
  if (req.session.views) {
    req.session.views++;
    res.send(`Views: ${req.session.views}`);
  } else {
    req.session.views = 1;
    res.send('Welcome! Refresh to count views.');
  }
});
💻

Example

This example shows a simple Express app using express-session to authenticate a user. When the user logs in with the correct username and password, their user ID is saved in the session. The app then remembers the login state on subsequent requests.

javascript
import express from 'express';
import session from 'express-session';

const app = express();
app.use(express.urlencoded({ extended: true }));

app.use(session({
  secret: 'my-secret',
  resave: false,
  saveUninitialized: false
}));

const USER = { username: 'user', password: 'pass' };

app.get('/', (req, res) => {
  if (req.session.userId) {
    res.send(`<h1>Welcome back, ${USER.username}!</h1><a href='/logout'>Logout</a>`);
  } else {
    res.send(`<form method='POST' action='/login'>
      <input name='username' placeholder='Username' required />
      <input name='password' type='password' placeholder='Password' required />
      <button type='submit'>Login</button>
    </form>`);
  }
});

app.post('/login', (req, res) => {
  const { username, password } = req.body;
  if (username === USER.username && password === USER.password) {
    req.session.userId = username;
    res.redirect('/');
  } else {
    res.send('Invalid credentials. <a href="/">Try again</a>');
  }
});

app.get('/logout', (req, res) => {
  req.session.destroy(() => {
    res.redirect('/');
  });
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Output
Server running on http://localhost:3000
⚠️

Common Pitfalls

Common mistakes when using session authentication in Express include:

  • Not setting a secret in express-session, which is required for security.
  • Using saveUninitialized: true unnecessarily, which can create empty sessions and waste resources.
  • Not destroying the session on logout, leaving the user still authenticated.
  • Forgetting to parse request bodies before accessing req.body in login routes.

Always ensure middleware order is correct: body parsers before session, and session before routes that use it.

javascript
/* Wrong: Missing secret and body parser */
import express from 'express';
import session from 'express-session';

const app = express();
app.use(session({ resave: false, saveUninitialized: true }));

app.post('/login', (req, res) => {
  // req.body is undefined here
  if (req.body.username === 'user') {
    req.session.userId = 'user';
    res.send('Logged in');
  } else {
    res.send('Fail');
  }
});

/* Right: Add secret and body parser */
app.use(express.urlencoded({ extended: true }));
app.use(session({ secret: 'secret', resave: false, saveUninitialized: false }));
📊

Quick Reference

  • express-session: Middleware to manage sessions.
  • secret: Required string to sign cookies.
  • resave: Usually false to avoid unnecessary saves.
  • saveUninitialized: Usually false to avoid empty sessions.
  • Store user info in req.session to track login.
  • Destroy session on logout with req.session.destroy().

Key Takeaways

Use express-session middleware with a secret to enable session authentication in Express.
Store user login state in req.session to keep users logged in across requests.
Always parse request bodies before accessing login data with express.urlencoded or similar.
Destroy sessions on logout to properly end user authentication.
Set resave and saveUninitialized options to false for better performance and security.