Express basics

Topic 1 of 4 in Express7 min readIntermediateFree course

Overview

Express is the most widely used web framework for Node.js. It’s deliberately small: it adds routing, middleware and handy request/response helpers on top of the node:http server you built by hand, and leaves everything else (databases, validation, auth) to you and the libraries you choose.

That minimalism is why Express remains a great place to learn — and why skills transfer easily to alternatives such as Fastify, Koa or Hono, which share the same ideas.

This course uses Express 5, the current major version. It’s very similar to Express 4, which you’ll still see in many tutorials; the differences that matter are pointed out along the way.

Setting up

Terminal
mkdir academy-api && cd academy-api
npm init -y
npm install express

Set "type": "module" in package.json, then create src/server.js:

JavaScript
import express from 'express';

const app = express();
const port = Number(process.env.PORT ?? 3000);

app.get('/', (req, res) => {
  res.json({ message: 'Hello from Express!' });
});

app.listen(port, () => {
  console.log(`API listening on http://localhost:${port}`);
});
Terminal
node --watch src/server.js
curl localhost:3000
# {"message":"Hello from Express!"}

Compare that with the raw http server: no URL parsing, no manual headers, no JSON.stringify — res.json() does it all.

Routes

A route is method + path + handler:

JavaScript
app.get('/courses', (req, res) => { /* list */ });
app.post('/courses', (req, res) => { /* create */ });
app.get('/courses/:id', (req, res) => { /* read one: req.params.id */ });
app.patch('/courses/:id', (req, res) => { /* update */ });
app.delete('/courses/:id', (req, res) => { /* remove */ });

Express checks routes in the order you define them and calls the first one that matches. If nothing matches, it sends a 404 with a small HTML page (you’ll replace that with JSON shortly). The next topic goes deeper into paths and parameters.

Sending responses

res is Node’s ServerResponse with extra helpers:

JavaScript
res.json({ id: 42 });                        // JSON + correct Content-Type
res.status(201).json(course);                // status + JSON (methods chain)
res.status(404).json({ error: 'Not found' });
res.sendStatus(204);                          // status with no body
res.send('<h1>Hi</h1>');                      // HTML or text
res.type('text').send('plain text');
res.set('Cache-Control', 'no-store');         // set a header
res.redirect(301, '/new-location');
res.sendFile(absolutePath);                   // stream a file
res.download(absolutePath, 'report.csv');     // with a "save as" name

As with raw Node, send exactly one response per request. A handler that forgets to respond leaves the client waiting; one that responds twice throws ERR_HTTP_HEADERS_SENT. A common slip:

JavaScript
app.get('/courses/:id', (req, res) => {
  const course = findCourse(req.params.id);
  if (!course) res.status(404).json({ error: 'Not found' }); // ✗ missing return
  res.json(course); // runs too → "headers already sent"
});

Write return res.status(404)… so the handler stops there.

Middleware in one paragraph

app.use(fn) registers middleware: a function that runs for every request (or every request under a path) before your route handlers. Middleware can read and modify req and res, end the request, or pass control on. Two built-in ones you’ll use in every API:

JavaScript
app.use(express.json());   // parse JSON request bodies into req.body
app.use(express.static('public')); // serve files from ./public

Without express.json(), req.body is undefined for JSON requests. Middleware gets its own topic shortly — it’s the heart of Express.

Static files

JavaScript
import path from 'node:path';

app.use(express.static(path.join(import.meta.dirname, '..', 'public')));

Now public/logo.png is served at /logo.png, with correct content types and caching headers. Use an absolute path so it works no matter which folder you start the server from.

Async handlers

Real handlers talk to databases and other services, so they’re async. In Express 5, if an async handler throws or its promise rejects, Express catches it and passes it to your error handler:

JavaScript
app.get('/courses/:id', async (req, res) => {
  const course = await db.findCourse(req.params.id); // if this throws, Express handles it
  res.json(course);
});

Express 4 was different: a rejected promise in a handler was not caught, so the request hung and the error was unhandled. Older code works around this with try…catch in every handler or packages like express-async-errors. With Express 5 you don’t need them.

The request lifecycle

For every request, Express:

  1. Runs middleware registered with app.use in order (express.json(), logging, auth…).
  2. Finds the first route whose method and path match, and calls its handler.
  3. If anything throws, skips to the error-handling middleware.
  4. If nothing responds, falls through to the 404 handler.

You’ll build steps 3 and 4 properly in Error handling in Express.

Separating the app from the server

A small habit that pays off when you write tests: create the app in one file and start listening in another.

JavaScript
// src/app.js
import express from 'express';
export const app = express();
app.use(express.json());
app.get('/health', (req, res) => res.json({ status: 'ok' }));
JavaScript
// src/server.js
import { app } from './app.js';
const port = Number(process.env.PORT ?? 3000);
app.listen(port, () => console.log(`Listening on ${port}`));

Tests can now import app and send requests to it without opening a real port — see Testing HTTP APIs.

Express or something else? Fastify is faster and has built-in schema validation; Hono runs on many platforms including edge runtimes; NestJS adds a full architecture on top. All share Express’s concepts: routes, handlers, middleware. Learn them here, and you can pick up any of them in a day.

Exercise

Your first Express API

Create an Express app with: GET / returning { name: 'Academy API', version: '1.0.0' }, GET /time returning the server time as ISO text, and a public folder served as static files. Read the port from PORT (default 3000) and add a dev script that uses watch mode.

JavaScript
import express from 'express';

const app = express();
// your code here

Summary

  • Express is a small framework on top of node:http that adds routing, middleware and response helpers.
  • app.get/post/patch/delete(path, handler) defines routes; handlers receive req and res.
  • res.json(), res.status(), res.send() and res.sendStatus() cover most responses.
  • app.use(middleware) runs code for every request — e.g. express.json() and express.static().
  • Express 5 forwards errors from async handlers to the error handler automatically.