Learn / Frameworks / Express / Express with TypeScript

Express · Lesson 11 of 15

Express with TypeScript

Typed Request handlers, a tsconfig that works for Node and extending Express types.

  • Intermediate
  • 16 min read
  • 3 objectives

Before this lessonLesson 10: Testing with Supertest

What you will learn

  • Type a handler
  • Augment Request
  • Run with tsx

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

TypeScript catches the req.body.title that might be missing. Express types are generic; you extend them for req.user.

Setup

npm install express
npm install -D typescript @types/express @types/node tsx
npx tsc --init
// tsconfig.json (ideas)
// { "compilerOptions": { "strict": true, "esModuleInterop": true, "module": "NodeNext" } }

Typed handlers

import { Router, type Request, type Response, type NextFunction } from "express";

interface Authed extends Request {
  userId?: number;
}

export function auth(req: Authed, res: Response, next: NextFunction) {
  // ...
  req.userId = 1;
  next();
}

Module augmentation

// types/express.d.ts
declare global {
  namespace Express {
    interface Request {
      userId?: number;
      requestId: string;
    }
  }
}
export {};
npx tsx src/index.ts          # dev
npx tsc && node dist/index.js  # prod
Up next · Lesson 12WebSocketsUpgrade an HTTP server to WebSocket and broadcast with care across processes.