Express Intro
Express is the most widely used web framework for Node.js. It sits on top of the node:http module you already know and adds a clean routing API, route parameters, middleware, body parsing and helpers like res.json(). Many other frameworks (and countless tutorials) follow its style, so learning it pays off.
Note: Express is an npm package, and packages can't be installed in this browser-based site. The Express code below is shown as normal code blocks with a simulated terminal session. At the end you'll find a runnable plain-Node version of the same API so you can see the behaviour for real.
Installing Express
mkdir hello-express && cd hello-express
npm init -y
npm install expressWrote to /home/you/hello-express/package.json
added 66 packages, and audited 67 packages in 2s
found 0 vulnerabilities
Express 5 is the current major version. It supports async route handlers out of the box: a rejected promise is passed to the error handler automatically.
Hello, Express
// app.mjs
import express from 'express';
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.listen(3000, () => console.log('Server on http://localhost:3000'));Compared to plain http, there's no if (req.method === 'GET' && …): app.get(path, handler) registers a route, and res.send() sets the status, Content-Type and Content-Length for you.
Routing and parameters
Express has one method per HTTP verb, and :name segments become req.params:
app.get('/users', (req, res) => res.json(users));
app.get('/users/:id', (req, res) => {
const user = users.find((u) => u.id === Number(req.params.id));
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
});
app.get('/search', (req, res) => {
// GET /search?q=node -> req.query.q === 'node'
res.json({ query: req.query.q ?? '' });
});| Express | Plain Node equivalent |
|---|---|
app.get('/a', fn) |
if (req.method === 'GET' && pathname === '/a') |
req.params.id |
a regex capture group |
req.query.q |
url.searchParams.get('q') |
res.status(404) |
res.statusCode = 404 |
res.json(data) |
setHeader('Content-Type', …) + end(JSON.stringify(data)) |
express.json() |
collect the body chunks and JSON.parse them |
A small JSON API
// api.mjs
import express from 'express';
const app = express();
app.use(express.json()); // parse JSON request bodies into req.body
const books = [{ id: 1, title: 'Eloquent JavaScript' }];
app.get('/books', (req, res) => res.json(books));
app.post('/books', (req, res) => {
const { title } = req.body ?? {};
if (!title) return res.status(400).json({ error: 'title is required' });
const book = { id: books.length + 1, title };
books.push(book);
res.status(201).json(book);
});
app.use((req, res) => res.status(404).json({ error: 'Not found' }));
app.listen(3000, () => console.log('API on http://localhost:3000'));node api.mjs &
curl http://localhost:3000/books
curl -X POST -H "Content-Type: application/json" -d '{"title":"Node Patterns"}' http://localhost:3000/books
curl -i http://localhost:3000/nopeAPI on http://localhost:3000
[{"id":1,"title":"Eloquent JavaScript"}]
{"id":2,"title":"Node Patterns"}
HTTP/1.1 404 Not Found
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 21
{"error":"Not found"}
Tip: Disable the
X-Powered-Byheader withapp.disable('x-powered-by')so you don't advertise your stack to attackers.
Organising routes with Router
As an app grows, group related routes in their own module:
// routes/books.mjs
import { Router } from 'express';
const router = Router();
router.get('/', (req, res) => res.json([]));
router.get('/:id', (req, res) => res.json({ id: req.params.id }));
export default router;
// app.mjs
import booksRouter from './routes/books.mjs';
app.use('/books', booksRouter); // mounted at /booksServing static files
express.static serves a folder of HTML, CSS, images and client JavaScript:
app.use(express.static('public')); // public/index.html -> GET /The same API without Express
To see the behaviour for real, here is a runnable plain-Node version of the books API. It's longer — which is exactly what Express saves you:
const http = require('node:http');
const books = [{ id: 1, title: 'Eloquent JavaScript' }];
const json = (res, status, data) => {
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(data));
};
const server = http.createServer(async (req, res) => {
const { pathname } = new URL(req.url, 'http://localhost');
if (pathname === '/books' && req.method === 'GET') return json(res, 200, books);
if (pathname === '/books' && req.method === 'POST') {
let raw = '';
for await (const chunk of req) raw += chunk;
const { title } = raw ? JSON.parse(raw) : {};
if (!title) return json(res, 400, { error: 'title is required' });
const book = { id: books.length + 1, title };
books.push(book);
return json(res, 201, book);
}
json(res, 404, { error: 'Not found' });
});
server.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
let r = await fetch(`${base}/books`);
console.log(r.status, await r.text());
r = await fetch(`${base}/books`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Node Patterns' }),
});
console.log(r.status, await r.text());
r = await fetch(`${base}/nope`);
console.log(r.status, await r.text());
server.close();
});200 [{"id":1,"title":"Eloquent JavaScript"}]
201 {"id":2,"title":"Node Patterns"}
404 {"error":"Not found"}
Alternatives
| Framework | Known for |
|---|---|
| Express | the classic, huge ecosystem of middleware |
| Fastify | speed and built-in JSON schema validation |
| Koa | tiny core by the Express authors, async-first |
| Hono | runs on Node, Deno, Bun and edge platforms |
| NestJS | structured, Angular-style architecture with TypeScript |
Test yourself
In Express, how do you read 42 from a request to /users/42 with the route /users/:id?
- req.query.id
- req.body.id
- req.params.id
- req.url.id
What does app.use(express.json()) do?
- Sends every response as JSON
- Parses JSON request bodies into
req.body - Validates JSON files on disk
- Enables CORS
Which call sends a 404 with a JSON body in Express?
- res.send(404, json)
- res.status(404).json({ error: 'Not found' })
- res.end(404)
- res.json(404)