Express Middleware with TypeScript: A Step-by-Step Guide
Express.js is a cornerstone of Node Express development, and combining it with TypeScript unlocks type safety and scalability. Middleware—the backbone of Express—handles tasks like authentication, logging, and error management. In this Express TypeScript tutorial, you’ll learn to create and manage middleware effectively
Join the 2.000+ members who have already signed up.
What is Middleware in Express?
Middleware in Express functions sit between the client request and the server response. They can:
- Modify request/response objects.
- Execute code (e.g., logging).
- End the request-response cycle.
-
Call the next middleware using
next()
.
Examples include authentication checks, request logging, and error handlers. With Express TypeScript, you gain static typing for safer, more maintainable code.
Installing Express and TypeScript + Basic Setup
Step 1: Initialize a Project
mkdir express-ts-middleware
cd express-ts-middleware
npm init -y
Step 2: Install Dependencies
npm install express
npm install -D typescript ts-node @types/express @types/node
Step 3: Configure TypeScript
Create
tsconfig.json
:
{
"compilerOptions": {
"target": "ES6",
"module": "CommonJS",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
}
}
Step 4: Create a Basic Server
In
src/index.ts
:
import express, { Application } from 'express';
const app: Application = express();
const port = 3000;
// Basic route
app.get('/', (req, res) => {
res.send('Hello from Express + TypeScript!');
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Run with
ts-node src/index.ts
.
Simple Middleware Example in TypeScript
Let’s create a logging middleware:
import { Request, Response, NextFunction } from 'express';
const logger = (req: Request, res: Response, next: NextFunction) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next(); // Pass control to the next middleware
};
// Apply middleware globally
app.use(logger);
Now, every request logs its method, URL, and timestamp.
Routing Middleware in Express TypeScript
Express router middleware lets you compartmentalize logic for specific routes.
Example: Authentication Middleware
Create
src/routes/auth.ts
:
import { Router, Request, Response, NextFunction } from 'express';
const router = Router();
// Route-specific middleware
const checkAuth = (req: Request, res: Response, next: NextFunction) => {
const isAuthenticated = true; // Replace with real logic
if (!isAuthenticated) return res.status(401).send('Unauthorized');
next();
};
router.get('/profile', checkAuth, (req, res) => {
res.send('User Profile');
});
export default router;
In index.ts
:
import authRouter from './routes/auth';
app.use('/auth', authRouter);
Error Handling in Express Using next()
Express relies on
error-handling middleware with four
arguments:
(err, req, res, next)
.
Step 1: Create a Custom Error Handler
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
Step 2: Trigger Errors in Routes
app.get('/error', (req, res, next) => {
try {
throw new Error('Demo error');
} catch (err) {
next(err); // Pass to error handler
}
});
Step 3: Handle 404 (Not Found)
Add this after all routes:
app.use((req, res) => {
res.status(404).json({ message: 'Route not found' });
});
Step 4: Test Error Responses
-
Visit
/error
to trigger a 500. - Visit an undefined route for a 404.
Conclusion and Best Practices
You’ve learned how to:
- Set up Express with TypeScript.
- Create global and route-specific middleware in Express.
- Implement Express router middleware for modular code.
- Handle errors and 404 responses.
Recommended Projects for Practice:
- REST API with JWT authentication middleware.
- Rate-limiting middleware for public endpoints.
- A logging service that tracks request/response times.
Express TypeScript empowers you to build scalable, type-safe apps. Explore advanced topics like dependency injection or decorators for even cleaner code.
– Cheers