Hello World
Let's take the smallest useful Express app apart line by line, then grow it a little: plain text, HTML and JSON responses, and a fallback for unknown URLs.
The four lines that matter
const express = require('express'); // 1. load the library
const app = express(); // 2. create an application
app.get('/', (req, res) => res.send('Hello World!')); // 3. register a route
app.listen(3000); // 4. start the HTTP server| Line | What happens |
|---|---|
express() |
returns an application — a function that can handle (req, res) plus methods like get, use, listen |
app.get(path, handler) |
when a GET request matches path, call handler(req, res) |
res.send(body) |
sends the response; picks a Content-Type based on the body type |
app.listen(port) |
creates a node:http server with the app as its request handler and returns that server |
app.listen() is only a shortcut. Under the hood it does http.createServer(app).listen(port) — which is why an Express app can be mounted into any Node HTTP server.
Running it
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
const server = app.listen(0, async () => {
const res = await fetch(`http://localhost:${server.address().port}/`);
console.log(res.status, res.headers.get('content-type'));
console.log(await res.text());
server.close();
});200 text/html; charset=utf-8
Hello World!
A string passed to res.send() is sent as text/html. If you want plain text, set the type first: res.type('text').send('Hello').
Three kinds of response
res.send() adapts to what you give it, while res.json() always produces JSON:
const express = require('express');
const app = express();
app.get('/text', (req, res) => res.type('text/plain').send('just text'));
app.get('/html', (req, res) => res.send('<h1>Hello</h1>'));
app.get('/json', (req, res) => res.json({ framework: 'express', version: 5 }));
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const path of ['/text', '/html', '/json']) {
const res = await fetch(base + path);
console.log(path.padEnd(6), res.headers.get('content-type').padEnd(32), await res.text());
}
server.close();
});/text text/plain; charset=utf-8 just text
/html text/html; charset=utf-8 <h1>Hello</h1>
/json application/json; charset=utf-8 {"framework":"express","version":5}
| Method | Body | Content-Type |
|---|---|---|
res.send('text') |
string | text/html (unless already set) |
res.send(Buffer) |
binary | application/octet-stream |
res.send({ a: 1 }) |
object | application/json (same as res.json) |
res.json(value) |
any JSON value | application/json |
res.end() |
nothing | none — ends the response raw |
Tip: For APIs, prefer
res.json()even for objects. It states your intent and also serialisesnull, numbers and booleans correctly.
What about unknown URLs?
If no route matches, Express's built-in "final handler" replies with 404 and a small HTML page saying Cannot GET /path. Most APIs replace that with their own JSON. Add a middleware after all routes — it only runs when nothing earlier answered:
const express = require('express');
const app = express();
app.get('/', (req, res) => res.json({ hello: 'world' }));
// Registered last: catches every request no route handled.
app.use((req, res) => {
res.status(404).json({ error: `No route for ${req.method} ${req.path}` });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const [method, path] of [['GET', '/'], ['GET', '/missing'], ['POST', '/']]) {
const res = await fetch(base + path, { method });
console.log(method, path, '->', res.status, await res.text());
}
server.close();
});GET / -> 200 {"hello":"world"}
GET /missing -> 404 {"error":"No route for GET /missing"}
POST / -> 404 {"error":"No route for POST /"}
POST / also hits the fallback: the route only handles GET.
Handing off to node:http
Because the app is just a request listener, you can pass it to http.createServer yourself. This is handy when you need the raw server object (for WebSockets or HTTPS):
const http = require('node:http');
const server = http.createServer(app);
server.listen(3000);Test yourself
What Content-Type does res.send('Hi') use by default?
- text/plain
- text/html
- application/json
- application/octet-stream
Where must a catch-all 404 middleware be registered?
- Before all routes
- After all routes
- Inside
app.listen - It doesn't matter
What does app.listen(3000) return?
- The Express app
- A Promise
- A Node
http.Server - Nothing