We use cookies to understand how the site is used and to display ads. Analytics and advertising only run after you accept. You can change your choice anytime. Privacy policy

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 server· Create a server.
import express from 'express';
const app = express();
app.listen(3000, () => console.log('running'));

Routing

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

Middleware

JSON body parser· Parse JSON bodies.
app.use(express.json());
CORS· Enable CORS.
import cors from 'cors';
app.use(cors());
Custom middleware· Log every request.
app.use((req, res, next) => { console.log(' '); next(); });

Request Handling

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

Error Handling

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

Testing

Supertest· Integration 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);
});