0
0
Expressframework~5 mins

Middleware composition for auth layers in Express

Choose your learning style9 modes available
Introduction

Middleware composition helps organize multiple small functions that check user identity and permissions. It keeps your code clean and easy to manage.

You want to check if a user is logged in before accessing a page.
You need to verify user roles like admin or editor before allowing actions.
You want to add multiple checks like token validation and permission checks in order.
You want to reuse authentication steps across different routes.
You want to handle errors or redirects if authentication fails.
Syntax
Express
app.use(middleware1, middleware2, middleware3);

// or for a single route
app.get('/path', middleware1, middleware2, handler);

Each middleware function receives req, res, and next to pass control.

Order matters: middleware runs in the order you list them.

Examples
This example checks if the user is logged in, then if they are an admin, before showing the admin page.
Express
function checkLoggedIn(req, res, next) {
  if (req.user) next();
  else res.status(401).send('Not logged in');
}

function checkAdmin(req, res, next) {
  if (req.user && req.user.role === 'admin') next();
  else res.status(403).send('Admin only');
}

app.get('/admin', checkLoggedIn, checkAdmin, (req, res) => {
  res.send('Welcome Admin');
});
You can group middleware in an array and spread it for cleaner code.
Express
const authMiddleware = [checkLoggedIn, checkAdmin];

app.get('/admin', ...authMiddleware, (req, res) => {
  res.send('Welcome Admin');
});
Sample Program

This Express app sets a fake user, then uses two middleware functions to check if the user is logged in and is an admin before showing a welcome message.

Express
import express from 'express';
const app = express();

// Simulate user data
app.use((req, res, next) => {
  req.user = { name: 'Alice', role: 'admin' };
  next();
});

function checkLoggedIn(req, res, next) {
  if (req.user) next();
  else res.status(401).send('Not logged in');
}

function checkAdmin(req, res, next) {
  if (req.user && req.user.role === 'admin') next();
  else res.status(403).send('Admin only');
}

app.get('/admin', checkLoggedIn, checkAdmin, (req, res) => {
  res.send(`Welcome Admin ${req.user.name}`);
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
OutputSuccess
Important Notes

Middleware functions must call next() to continue the chain.

Always handle errors or send responses to avoid hanging requests.

Use middleware composition to keep your auth logic reusable and clear.

Summary

Middleware composition lets you run multiple auth checks in order.

Use small middleware functions for each auth step.

Group middleware for cleaner route definitions.