Skip to main content

Lesson 8 of 8

Practice & Quiz - TypeScript with Node.js & Express

Solidify your Node.js + Express TypeScript skills - @types/node, typed route handlers, middleware, env validation, and service/controller separation - with a hands-on example and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical: Typed Middleware Chain

Practical: Typed Middleware Chain
// A complete typed middleware pipeline: request ID → auth → route → error
import { Request, Response, NextFunction, Router } from "express";
import { randomUUID } from "node:crypto";
import jwt from "jsonwebtoken";

// 1. Augment Express.Request with custom fields
declare global {
  namespace Express {
    interface Request {
      requestId: string;
      user?: { id: number; role: "member" | "admin" };
    }
  }
}

// 2. Request ID middleware - runs on every request
export function requestId(req: Request, _res: Response, next: NextFunction): void {
  req.requestId = randomUUID();
  next();
}

// 3. Auth middleware - attaches req.user
export function requireAuth(req: Request, res: Response, next: NextFunction): void {
  const token = req.headers.authorization?.replace("Bearer ", "");
  if (!token) { res.status(401).json({ error: "Unauthorized" }); return; }
  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET!) as {
      sub: number; role: "member" | "admin";
    };
    req.user = { id: payload.sub, role: payload.role };
    next();
  } catch {
    res.status(401).json({ error: "Invalid token" });
  }
}

// 4. Admin-only guard middleware
export function requireAdmin(req: Request, res: Response, next: NextFunction): void {
  if (req.user?.role !== "admin") {
    res.status(403).json({ error: "Forbidden" });
    return;
  }
  next();
}

// 5. Typed route using the middleware chain
const router = Router();
router.delete(
  "/tasks/:id",
  requireAuth,
  requireAdmin,
  async (req: Request<{ id: string }>, res: Response, next: NextFunction) => {
    const id = parseInt(req.params.id, 10);
    if (isNaN(id)) { res.status(400).json({ error: "Invalid ID" }); return; }
    try {
      await taskService.delete(id);
      res.status(204).send();
    } catch (err) { next(err); }
  }
);

Module Quiz

Module Quiz
Question 1 of 5

Why must Node.js tsconfig have `"lib": ["ES2022"]` WITHOUT `"DOM"` in the array?

Tip

Tip

Practice Practice Quiz TypeScript with Nodejs Express in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

TypeScript = JavaScript + static types → fewer bugs, better tooling

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz TypeScript with Nodejs Express from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Practice Quiz TypeScript with Nodejs Express is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done