Express.js

Fast, unopinionated, minimalist web framework for Node.js

Express.js Overview

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. With a myriad of HTTP utility methods and middleware at your disposal, creating a robust API is quick and easy.

Initial release

November 2010

Stable release

4.18.2 (June 2023)

Written in

JavaScript

License

MIT License

Key Features

Common Use Cases

RESTful APIs

Building backend services for web/mobile apps.

Server-Side Rendering

Traditional web applications with templating.

Microservices

Lightweight services in a distributed system.

Proxy Servers

Routing requests between services.

Example Code

// Basic Express server example
const express = require('express');
const app = express();
const port = 3000;

// Middleware for parsing JSON
app.use(express.json());

// Simple route
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// Route with parameters
app.get('/users/:userId', (req, res) => {
  res.send(`User ID: ${req.params.userId}`);
});

// POST route with JSON body
app.post('/users', (req, res) => {
  const { name, email } = req.body;
  // Save user to database...
  res.status(201).json({ id: 1, name, email });
});

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

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

// Middleware example
function logger(req, res, next) {
  console.log(`${req.method} ${req.path}`);
  next();
}

app.use(logger);

// Router example
const router = express.Router();

router.get('/', (req, res) => {
  res.send('API home');
});

router.get('/products', (req, res) => {
  res.json([{ id: 1, name: 'Product 1' }]);
});

app.use('/api', router);

Learning Resources