Skip to main content

Overview

Express Zod API provides two approaches for integrating native Express middlewares, depending on their purpose and scope. This guide shows you how to use both methods effectively.

Two Integration Methods

1. Global Middlewares with beforeRouting

Use this for middlewares that:
  • Establish their own routes (like Swagger UI)
  • Globally modify behavior
  • Parse additional request formats (like cookies)
  • Need to run before all API routes

2. Endpoint-Specific with addExpressMiddleware()

Use this for middlewares that:
  • Process specific endpoints
  • Need to provide context to handlers
  • Require error transformation
  • Should be tested with your endpoints

Global Middlewares: beforeRouting

The beforeRouting option runs code before your routing is established.

Basic Usage

Serving Documentation

Serve your API documentation using Swagger UI:

Custom Routes

Add custom routes outside your main routing structure:

Using Child Logger

Access request-specific child loggers when configured:

Endpoint-Specific: addExpressMiddleware()

For middlewares that need to interact with specific endpoints, use the addExpressMiddleware() method (alias: use()).

Basic Usage

OAuth2 Integration

Integrate OAuth2 JWT bearer authentication:

CORS Configuration

While Express Zod API handles CORS natively, you can use the Express middleware for advanced cases:
Prefer the built-in CORS configuration in most cases—it’s designed to work seamlessly with the framework.

Request Compression

Apply compression to specific endpoints:

Body Parser Alternatives

Use alternative body parsers for specific content types:

Helmet Security

Add security headers with Helmet:

Request ID Middleware

Add request IDs for tracking:

Context Providers

The provider option extracts data from the Express request:

Error Transformers

Transform Express middleware errors to HTTP errors:

Multiple Middlewares

Chain multiple Express middlewares:

Avoid: CORS Middleware

Don’t use Express CORS middleware in beforeRouting—use the framework’s built-in option instead:

Static File Serving

Serve static files without Express middleware:

Passport.js Integration

Integrate Passport authentication strategies:

Best Practices

Choose the Right Method

Use beforeRouting for global setup and addExpressMiddleware() for endpoint-specific logic.

Provide Context

Always use the provider option to make middleware data available to handlers.

Transform Errors

Use the transformer option to convert Express errors to HttpError instances.

Prefer Native Features

Use the framework’s built-in features for CORS, compression, and file uploads when possible.

Testing

Test endpoints with Express middlewares:

Next Steps