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.
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
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.
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.
Finished this lesson?