Back to list

Express.js Middleware Pattern

Lv.5505@mukitaro15 playsDec 28, 2025

Express.js middleware chain pattern. Node.js most popular web framework.

preview.js
JavaScript
1const express = require('express');
2const app = express();
3
4const logger = (req, res, next) => {
5 console.log(`${req.method} ${req.url}`);
6 next();
7};
8
9const authenticate = (req, res, next) => {
10 const token = req.headers.authorization;
11 if (!token) {
12 return res.status(401).json({ error: 'Unauthorized' });
13 }
14 req.user = { id: 1, name: 'John' };
15 next();
16};
17
18app.use(logger);
19app.use('/api', authenticate);
20
21app.get('/api/profile', (req, res) => {
22 res.json(req.user);
23});
24
25app.listen(3000);

Custom problems are not included in rankings