Your first Express route
Node has a built-in http module that can do all this. It also makes you parse URLs, headers, and bodies by hand. Express is a thin layer on top that takes care of the boring parts and gives you a clean way to declare routes. Almost every Node backend in production starts here.
import express from 'express';
import { Server } from 'http';
export const app = express();
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
let serverInstance: Server | null = null;
export function startServer(port: number = 3000): Server {
serverInstance = app.listen(port, () => {
console.log('Server running on http://localhost:' + port);
});
return serverInstance;
}
export function stopServer() {
if (serverInstance) {
serverInstance.close();
}
}
if (require.main === module) {
startServer(3000);
}The smallest useful Express server. A health check that returns JSON.
Read app.get carefully. A method (get), a path (/health), and a handler function that gets req and res. Every Express route ever written has this same shape. Once you know it, you know how to add any endpoint.
Both send a response. res.send sends a string. res.json takes an object, serializes it to JSON, and sets the Content-Type header to application/json so the client knows how to parse it. When you are returning structured data, always reach for res.json.
Quiz: Quiz
Loading practice…
Validation checklist: Get a health check responding
Loading practice…