beginner
backend

What is Express.js?

Understanding Express.js, the minimalist web framework for Node.js backend development

express fundamentals
12 min read

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 & Fast
Unopinionated framework with minimal overhead for maximum performance
Flexible
Use any database, template engine, or architecture pattern you prefer
Battle-Tested
Powers millions of applications with extensive middleware ecosystem

Express.js Core Concepts

Your First Express Server

Here's how simple it is to create a web server with Express:

javascript
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}`) })

HTTP Methods and Routing

Express provides methods for all HTTP verbs:

GET - Retrieve Data
javascript
// 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.

javascript
// 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 files
Middleware Flow
RequestMiddleware 1Middleware 2Route HandlerResponse

Express vs Other Frameworks

FeatureExpressFastifyNestJS
Learning CurveEasyEasyModerate
PerformanceGoodExcellentGood
TypeScript@types/expressBuilt-inNative
ArchitectureMinimalMinimalOpinionated
EcosystemMassiveGrowingStrong

When to Use Express


Quick Start Example

Here's a complete Express API example:

javascript
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

Continue Learning
Now that you understand what Express.js is, let's set up your development environment and build your first Express server!

Next Lesson

Setting Up Express Development Environment