Express.js Web Framework

45.0.0 · active · verified Sun Apr 19

Express.js is a minimalist, unopinionated, and flexible Node.js web application framework, designed for building robust APIs and web applications. It provides a thin layer of fundamental web application features atop Node.js's built-in HTTP module, emphasizing speed and extensibility through its middleware-centric architecture. The current stable release is v5.2.1, with the v5 branch representing a major overhaul focused on simplifying the codebase and improving security. The v4.x branch (currently v4.22.1) is also actively maintained, primarily for security patches and critical bug fixes, serving projects that haven't yet migrated to v5. Its unopinionated nature contrasts with more prescriptive frameworks, offering maximum flexibility in project structure and choice of components, allowing developers to easily extend functionality for tasks like routing, parsing request bodies, handling sessions, and serving static files.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic Express.js server using TypeScript and ES modules. It includes JSON body parsing middleware, a custom logging middleware, a GET route, a POST route handling JSON data, and a fundamental error handler, showcasing a typical setup for an Express application.

import express, { Request, Response, NextFunction } from 'express';

const app = express();
const port = 3000;

// Middleware to parse JSON bodies
app.use(express.json());

// A simple logger middleware
app.use((req: Request, res: Response, next: NextFunction) => {
  console.log(`${req.method} ${req.url} at ${new Date().toISOString()}`);
  next();
});

// Define a GET route
app.get('/', (req: Request, res: Response) => {
  res.send('Hello from Express v5!');
});

// Define a POST route with a request body
app.post('/data', (req: Request, res: Response) => {
  if (req.body && typeof req.body === 'object' && 'message' in req.body) {
    res.json({ received: req.body.message, status: 'success' });
  } else {
    res.status(400).json({ error: 'Message not found in request body.' });
  }
});

// Error handling middleware (should be last)
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

app.listen(port, () => {
  console.log(`Express server listening on http://localhost:${port}`);
});

view raw JSON →