Typing Requests, Middleware, and Error Handling - Textnotes

Typing Requests, Middleware, and Error Handling


Learn how to build type-safe Express.js applications with TypeScript. This module explains typing request and response objects, middleware typing, and centralized error handling

1. Typing Request and Response

TypeScript allows typing the Request and Response objects in Express for better type safety.

Installation


npm install express
npm install --save-dev @types/express

Example


import express, { Request, Response } from "express";

const app = express();

app.get("/user/:id", (req: Request, res: Response) => {
const userId: string = req.params.id;
res.json({ id: userId, name: "Muni" });
});

app.listen(3000, () => console.log("Server running on port 3000"));

Typing requests and responses ensures safe access to params, body, query, and response methods.

2. Middleware Typing

Middleware functions can be typed with Request, Response, and NextFunction for proper type checking.

Example


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

const loggerMiddleware = (req: Request, res: Response, next: NextFunction) => {
console.log(`${req.method} ${req.url}`);
next();
};

app.use(loggerMiddleware);

Typing middleware ensures correct handling of request, response, and next callbacks.

Example: Typed Request Body


interface UserBody {
name: string;
age: number;
}

app.post("/user", (req: Request<{}, {}, UserBody>, res: Response) => {
const { name, age } = req.body;
res.json({ message: `User ${name} added with age ${age}` });
});

Typed request bodies prevent invalid data access and provide IntelliSense support.

3. Centralized Error Handling

TypeScript helps enforce type safety in error-handling middleware.

Example


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

interface CustomError extends Error {
status?: number;
}

const errorHandler = (err: CustomError, req: Request, res: Response, next: NextFunction) => {
const status = err.status || 500;
res.status(status).json({ message: err.message });
};

app.use(errorHandler);

Throwing Custom Errors


app.get("/error", (req, res, next) => {
const err: CustomError = new Error("Something went wrong");
err.status = 400;
next(err);
});

Centralized error handling ensures consistent responses and type-safe error management across the application.

Conclusion

Using Express.js with TypeScript provides strong type safety for requests, responses, middleware, and error handling. Typed Express applications reduce runtime errors, improve maintainability, and enhance developer productivity.