Express
04 / 07

Setup & Basics

Express.js Setup & Basics

Express is a minimal, unopinionated web framework for Node.js. It provides a thin layer of fundamental web application features - routing, middleware, and HTTP utilities - without obscuring the Node.js features you already know.

Installation & First Server

# Initialize project
npm init -y
npm install express
npm install -D @types/express typescript ts-node nodemon  # TypeScript setup

# nodemon for auto-restart in development
npx nodemon src/index.ts
// src/index.js - Basic Express server
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

// Built-in middleware
app.use(express.json());                         // Parse JSON request bodies
app.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies
app.use(express.static('public'));               // Serve static files

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

// Start server
app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});

TypeScript Setup

// src/index.ts - Express with TypeScript
import express, { Request, Response, NextFunction } from 'express';

const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json());

app.get('/', (req: Request, res: Response) => {
  res.json({ message: 'Hello, World!', timestamp: new Date().toISOString() });
});

app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});

export default app;

Request & Response Objects

Express extends Node's http.IncomingMessage and http.ServerResponse with convenient properties and methods. Understanding these is fundamental to working with Express.

app.post('/api/users/:id/posts', (req, res) => {
  // Request properties
  console.log(req.params);      // { id: '42' } - URL params
  console.log(req.query);       // { page: '1', limit: '10' } - query string
  console.log(req.body);        // { title: 'Hello' } - parsed request body
  console.log(req.headers);     // Request headers
  console.log(req.method);      // 'POST'
  console.log(req.path);        // '/api/users/42/posts'
  console.log(req.url);         // Full URL with query string
  console.log(req.ip);          // Client IP address
  console.log(req.cookies);     // Parsed cookies (requires cookie-parser)

  // Response methods
  res.status(201)               // Set status code (chainable)
    .set('X-Custom-Header', 'value')  // Set response header
    .json({ id: 1, title: 'Hello' }); // Send JSON (sets Content-Type)

  // Other response methods:
  // res.send('text')           - Send string/Buffer/object
  // res.sendFile('/path')      - Send a file
  // res.redirect('/new-url')   - 302 redirect
  // res.redirect(301, '/new')  - Permanent redirect
  // res.render('view', data)   - Render a template
  // res.end()                  - End response with no body
  // res.download('/path')      - Prompt file download
});

Project Structure

A scalable Express project separates concerns into layers: routes define endpoints, controllers handle request/response logic, services contain business logic, and models/repositories handle data access.

src/
  index.ts           # Server entry point
  app.ts             # Express app setup (routes, middleware)
  routes/
    users.ts         # /api/users routes
    auth.ts          # /api/auth routes
  controllers/
    usersController.ts
    authController.ts
  services/
    usersService.ts
    emailService.ts
  middleware/
    auth.ts          # JWT verification
    validate.ts      # Request validation
    errorHandler.ts  # Global error handler
  models/
    User.ts
  config/
    database.ts
    env.ts

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free