Skip to content
>_devvkit
$devvkit learn --librarie express.js-guide

Express.js Guide

[nodejs][http][server][api]
JavaScript / TypeScript
Install
npm install express
npm install -D @types/express

Express is the most popular Node.js web framework and the foundation for NestJS, Next.js API routes, and more.

The middleware pattern is its killer feature. Every request passes through a pipeline of functions that can inspect, modify, or short-circuit it.

Express 5 introduces async error handling and improved path matching.

Setup

Basic serverCreate a server.
import express from 'express';
const app = express();
app.listen(3000, () => console.log('running'));

Routing

GET routeHandle GET requests.
app.get('/users', (req, res) => { res.json({ users: [] }); });
Route paramsCapture dynamic segments.
app.get('/users/:id', (req, res) => res.json({ id: req.params.id }));
Query paramsAccess query string.
app.get('/search', (req, res) => res.json({ q: req.query.q }));

Middleware

JSON body parserParse JSON bodies.
app.use(express.json());
CORSEnable CORS.
import cors from 'cors';
app.use(cors());
Custom middlewareLog every request.
app.use((req, res, next) => { console.log(' '); next(); });

Request Handling

POST with JSONHandle POST with payload.
app.post('/users', (req, res) => { const { name } = req.body; res.status(201).json({ id: 1, name }); });

Error Handling

Error middlewareCatch errors globally.
app.use((err, req, res, next) => { console.error(err.stack); res.status(500).json({ error: 'Broken' }); });

Testing

SupertestIntegration test.
import request from 'supertest';
import app from '../app';
it('returns users', async () => {
  const res = await request(app).get('/users');
  expect(res.status).toBe(200);
});