What is Express.js?
Understanding Express.js, the minimalist web framework for Node.js backend development
- Course
- Express fundamentals
- Lesson
- 1 of 9
- Level
- Beginner
- Reading time
- 12 minutes
Introduction to Express.js ¶
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. It's the de facto standard server framework for Node.js.
Learning objectives
- Understand what Express.js is and its role in backend development
- Learn about the middleware architecture
- Understand routing and HTTP methods
- Recognize when Express is the right choice for your project
Why Express.js? ¶
- Minimal and fast: an unopinionated framework with minimal overhead.
- Flexible: use any database, template engine or architecture pattern you prefer.
- Battle-tested: powers millions of applications, with an extensive middleware ecosystem.
Express.js Core Concepts ¶
Your First Express Server ¶
Here's how simple it is to create a web server with Express:
const express = require("express")
const app = express()
const PORT = 3000
// Define a route
app.get("/", (req, res) => {
res.send("Hello World!")
})
// Start the server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`)
})Key insight
HTTP Methods and Routing ¶
Express provides methods for all HTTP verbs:
// Get all users
app.get('/api/users', (req, res) => {
res.json(users);
});
// Get user by ID
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === req.params.id);
if (!user) return res.status(404).json({ error: 'Not found' });
res.json(user);
});Middleware Architecture ¶
Middleware functions are the backbone of Express. They have access to the request, response, and the next middleware in the chain.
// Custom logging middleware
const logger = (req, res, next) => {
console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`)
next() // Pass control to next middleware
}
// Apply middleware
app.use(logger)
// Built-in middleware
app.use(express.json()) // Parse JSON bodies
app.use(express.urlencoded({ extended: true })) // Parse URL-encoded bodies
app.use(express.static("public")) // Serve static filesA request passes through each layer in order:
- Request
- Middleware 1
- Middleware 2
- Route handler
- Response
Express vs Other Frameworks ¶
| Feature | Express | Fastify | NestJS |
|---|---|---|---|
| Learning curve | Easy | Easy | Moderate |
| Performance | Good | Excellent | Good |
| TypeScript | @types/express | Built-in | Native |
| Architecture | Minimal | Minimal | Opinionated |
| Ecosystem | Massive | Growing | Strong |
When to Use Express ¶
Quick Start Example ¶
Here's a complete Express API example:
const express = require("express")
const cors = require("cors")
const helmet = require("helmet")
const app = express()
const PORT = process.env.PORT || 3000
// Middleware
app.use(helmet()) // Security headers
app.use(cors()) // Enable CORS
app.use(express.json()) // Parse JSON
// In-memory data store
let todos = [
{ id: 1, title: "Learn Express", completed: false },
{ id: 2, title: "Build an API", completed: false },
]
// Routes
app.get("/api/todos", (req, res) => {
res.json(todos)
})
app.get("/api/todos/:id", (req, res) => {
const todo = todos.find((t) => t.id === parseInt(req.params.id))
if (!todo) return res.status(404).json({ error: "Todo not found" })
res.json(todo)
})
app.post("/api/todos", (req, res) => {
const todo = {
id: todos.length + 1,
title: req.body.title,
completed: false,
}
todos.push(todo)
res.status(201).json(todo)
})
app.patch("/api/todos/:id", (req, res) => {
const todo = todos.find((t) => t.id === parseInt(req.params.id))
if (!todo) return res.status(404).json({ error: "Todo not found" })
if (req.body.title) todo.title = req.body.title
if (req.body.completed !== undefined) todo.completed = req.body.completed
res.json(todo)
})
app.delete("/api/todos/:id", (req, res) => {
const index = todos.findIndex((t) => t.id === parseInt(req.params.id))
if (index === -1) return res.status(404).json({ error: "Todo not found" })
todos.splice(index, 1)
res.status(204).send()
})
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).json({ error: "Something went wrong!" })
})
// Start server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`)
})Next Steps ¶
Next lesson
Setting up an Express development environment
Now that you understand what Express.js is, let's set up your development environment and build your first Express server!
Further reading