Lesson 8 of 20

Introduction to Express.js

What is Express.js?

Express.js is the most popular web framework for Node.js. It provides a minimal, flexible set of tools for building web applications and APIs. Express simplifies routing, middleware, and request handling that would be tedious with the raw http module.

Express is unopinionated — it does not force a specific project structure or tool choice. You pick your own template engine, database, and folder structure. This flexibility is why Express powers millions of applications.

Example
// Install Express
// npm install express

const express = require('express');
const app = express();
const PORT = 3000;

// Define routes
app.get('/', (req, res) => {
  res.send('<h1>Welcome to Express!</h1>');
});

app.get('/about', (req, res) => {
  res.send('<h1>About Page</h1>');
});

app.get('/api/users', (req, res) => {
  res.json([
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' }
  ]);
});

// Start the server
app.listen(PORT, () => {
  console.log(`Express server running on http://localhost:${PORT}`);
});
  • express() — Creates an Express application instance
  • app.get() — Handle GET requests to a specific path
  • app.post() — Handle POST requests
  • res.send() — Send a response (auto-detects content type)
  • res.json() — Send a JSON response
  • app.listen() — Start the server on a port
Notes
  • Express is built on top of Node.js's http module. It adds a layer of convenience without sacrificing performance.

Middleware Concept

Middleware functions are the backbone of Express. They are functions that run between receiving a request and sending a response. Middleware can modify the request, the response, end the request-response cycle, or pass control to the next middleware.

Think of middleware as a pipeline — each request passes through a series of functions before reaching the final route handler.

Example
const express = require('express');
const app = express();

// Built-in middleware: Parse JSON request bodies
app.use(express.json());

// Custom middleware: Log every request
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} ${req.method} ${req.url}`);
  next(); // Pass control to the next middleware
});

// Route handler (also middleware)
app.get('/', (req, res) => {
  res.json({ message: 'Hello World' });
});

// Middleware order matters!
// 1. express.json() parses the body
// 2. Logger logs the request
// 3. Route handler sends the response

app.listen(3000);
Notes
  • Always call next() in middleware unless you want to end the request. Forgetting next() will cause the request to hang.