Node.js Express
Express is the most popular web framework for Node.js. It is minimal and flexible: it gives you routing, middleware and helpers for requests and responses, and lets you add only what you need. Many larger frameworks, such as NestJS, are built on top of it.
Install Express
mkdir express-app && cd express-app
npm init -y
npm pkg set type=module
npm install expressadded 64 packages in 3s
Hello World with Express
app.get registers a handler for GET requests to a path. res.send sets the content type automatically and ends the response.
// server.js
import express from 'express';
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
app.listen(PORT, () => console.log(`Listening on http://localhost:${PORT}`));Listening on http://localhost:3000 GET / Hello, Express!
Sending Different Responses
app.get('/html', (req, res) => {
res.send('<h1>Portfolio</h1><p>Built with Express</p>');
});
app.get('/api/profile', (req, res) => {
res.json({ name: 'Naeem Amin', skills: ['Node.js', 'React'] });
});
app.get('/old-page', (req, res) => {
res.redirect(301, '/html');
});
app.get('/secret', (req, res) => {
res.status(403).json({ error: 'Forbidden' });
});GET /api/profile
{"name":"Naeem Amin","skills":["Node.js","React"]}
GET /secret (403)
{"error":"Forbidden"}The Request Object
- req.params — route parameters, e.g. /users/:id
- req.query — query string values, e.g. ?page=2
- req.body — parsed request body (needs express.json() middleware)
- req.headers / req.get("Authorization") — request headers
- req.method, req.path, req.ip — request details
Serving Static Files
express.static serves files such as HTML, CSS, images and a built React app straight from a folder.
import path from 'node:path';
app.use(express.static(path.join(import.meta.dirname, 'public')));
// public/style.css is now available at /style.cssGET /style.css
body { font-family: system-ui; }Express 4 vs Express 5
Express 5 is now the current major version. The biggest change for everyday code is that rejected promises in async route handlers are passed to your error handler automatically. The examples in this tutorial work on both versions unless noted.
Frequently asked questions
What is Express.js used for?
Express is used to build web servers and APIs in Node.js. It simplifies routing, middleware, request parsing and sending responses.
What is the difference between res.send and res.json?
res.json always sends JSON with the correct Content-Type. res.send accepts strings, buffers or objects and guesses the type; use res.json for APIs to be explicit.
Is Express still worth learning?
Yes. It remains the most widely used Node.js framework, its concepts transfer to alternatives like Fastify and Koa, and many tutorials, jobs and libraries assume it.