Express is a small, fast web framework for Node.js. It makes routing, request handling and responses much simpler than the plain http module.
Install
npm install express
A basic app
const app = express();- Add routes:
app.get('/', (req, res) => res.send('Hello')) - Start:
app.listen(3000)
Useful response methods
res.send(text or HTML)res.json(object)— sends JSON with the right headerres.status(404).send('Not found')res.redirect('/login')res.sendFile(path),res.download(path)res.render('view', data)— with a template engine
Built-in middleware
app.use(express.json())— read JSON bodies intoreq.bodyapp.use(express.urlencoded({ extended: true }))— read HTML form bodiesapp.use(express.static('public'))— serve CSS, JS and images frompublic
Use node --watch app.js (or nodemon) so the server restarts on every save.
Example
Example — Your first Express app
JavaScript
// app.js
import express from 'express';
const app = express();
app.use(express.json());
app.use(express.static('public'));
app.get('/', (req, res) => {
res.send('<h1>Welcome to my Express app</h1>');
});
app.get('/api/time', (req, res) => {
res.json({ now: new Date().toISOString() });
});
app.use((req, res) => {
res.status(404).json({ error: 'Route not found' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server: http://localhost:${PORT}`));
/ shows a heading, /api/time returns {"now":"2026-12-03T..."}, files in public/ are served directly, and other URLs return a 404 JSON error.