Skip to content

Express.js

This content is for Backend. Switch to the latest version for up-to-date documentation.

Express.js is a minimal web framework for Node.js.

It gives you a clean way to:

  • define routes (URLs)
  • add middleware (code that runs before/after routes)
  • send responses (HTML, JSON, files)
Terminal window
npm install express
import express from 'express';
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Diagram

A route matches a request by:

  • HTTP method (GET/POST/PUT/PATCH/DELETE)
  • path (like /users)

Examples:

app.get('/health', (req, res) => res.json({ ok: true }));
app.post('/users', (req, res) => {
res.status(201).json({ message: 'User created' });
});

Use route params when you want to address one specific resource.

app.get('/users/:id', (req, res) => {
const { id } = req.params;
res.json({ id, name: 'Example' });
});

Request:

GET /users/42

req.params:

{ "id": "42" }

Use query params for filtering, sorting, pagination.

app.get('/users', (req, res) => {
const { role, page = '1' } = req.query;
res.json({ role, page });
});

Request:

GET /users?role=admin&page=2

Every route handler receives:

  • req (request): incoming data
  • res (response): what you send back

Common things you use:

app.get('/info', (req, res) => {
res.json({
method: req.method,
path: req.path,
headers: req.headers,
});
});

To read JSON bodies, you need the JSON middleware:

app.use(express.json());
app.post('/echo', (req, res) => {
res.json({ youSent: req.body });
});

Middleware is a function that runs during request processing.

It can:

  • log requests
  • check auth
  • attach data to req
  • stop the request with a response
  • or pass control to the next handler
app.use((req, res, next) => {
console.log(`${req.method} ${req.path}`);
next();
});
Diagram
function requireApiKey(req, res, next) {
if (req.headers['x-api-key'] !== 'secret') {
return res.status(401).json({ error: 'Unauthorized' });
}
next();
}
app.get('/private', requireApiKey, (req, res) => {
res.json({ secretData: 123 });
});

As your API grows, you usually group routes into a router.

Example:

import express from 'express';
const usersRouter = express.Router();
usersRouter.get('/', (req, res) => res.json([{ id: 1, name: 'Alice' }]));
usersRouter.get('/:id', (req, res) => res.json({ id: req.params.id }));
export default usersRouter;

Then mount it:

import usersRouter from './routes/users.js';
app.use('/users', usersRouter);

This creates:

  • GET /users
  • GET /users/:id
res.status(200).json({ ok: true });
res.status(201).json({ created: true });
res.status(404).json({ error: 'Not found' });

Express treats a function with four arguments as an error handler.

app.get('/boom', (req, res) => {
throw new Error('Something broke');
});
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Internal Server Error' });
});

If you have a folder like public/, you can serve files from it:

app.use(express.static('public'));

Then public/logo.png becomes:

GET /logo.png

  • REST APIs for web and mobile apps
  • Backend-for-frontend (BFF) servers
  • Prototypes and small-to-medium backends (and sometimes parts of larger systems)

Industry examples (companies using Node/Express-style backends):

  • Netflix: has used Node.js widely for web services
  • PayPal: early well-known Node.js adoption for web apps
  • Uber: uses Node.js for various services
  • NestJS: A more structured Node.js framework (TypeScript-first) inspired by Angular.
Built with passion by Ngineer Lab