|
14 | 14 |
|
15 | 15 | - [Quick Start](#quick-start)
|
16 | 16 | - [Why Use `nextjs-centralized-error-handler` with Next.js Middleware?](#why-use-nextjs-centralized-error-handler-with-nextjs-middleware)
|
| 17 | +- [Comparison with Next.js 13 Middleware](#comparison-with-nextjs-13-middleware) |
17 | 18 | - [Key Advantages of `nextjs-centralized-error-handler`](#key-advantages-of-nextjs-centralized-error-handler)
|
18 | 19 | - [Traditional Approach vs. `nextjs-centralized-error-handler`](#traditional-approach-vs-nextjs-centralized-error-handler)
|
19 | 20 | - [Traditional Approach in Express (Using Middleware)](#traditional-approach-in-express-using-middleware)
|
@@ -115,6 +116,115 @@ By combining Next.js middleware with `nextjs-centralized-error-handler`, you ach
|
115 | 116 |
|
116 | 117 | ---
|
117 | 118 |
|
| 119 | +## Comparison with Next.js 13 Middleware |
| 120 | +
|
| 121 | +Next.js 13 introduces global middleware, enabling request-level interception for tasks such as authentication and general validation. Below is a comparison showing how Next.js 13 middleware differs from `nextjs-centralized-error-handler` and when to use each. |
| 122 | +
|
| 123 | +### Next.js 13 Middleware Example |
| 124 | +
|
| 125 | +Next.js 13 middleware can be defined globally and applied across all routes that match a specified pattern. This is useful for high-level operations like logging or authorization. |
| 126 | +
|
| 127 | +```javascript |
| 128 | +// middleware.js (placed at the root of the app) |
| 129 | +import { NextResponse } from 'next/server'; |
| 130 | +
|
| 131 | +export function middleware(req) { |
| 132 | + // Example of request validation or general logging |
| 133 | + if (!req.headers.get('Authorization')) { |
| 134 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); |
| 135 | + } |
| 136 | +
|
| 137 | + return NextResponse.next(); // Continue to the route handler |
| 138 | +} |
| 139 | +
|
| 140 | +// Optional: Configure route matching |
| 141 | +export const config = { |
| 142 | + matcher: '/api/:path*', // Applies middleware only to /api/* routes |
| 143 | +}; |
| 144 | +``` |
| 145 | +
|
| 146 | +### Comparison with nextjs-centralized-error-handler |
| 147 | +
|
| 148 | +While Next.js middleware is useful for global, high-level tasks, nextjs-centralized-error-handler enables route-specific error handling with custom error classes for fine-grained control. Here’s how both work together: |
| 149 | +
|
| 150 | +| Feature | Next.js 13 Middleware | nextjs-centralized-error-handler | |
| 151 | +|-----------------------------|------------------------------------------------|----------------------------------------------------------| |
| 152 | +| Scope | Global, based on route pattern matching | Route-specific, applied individually to each handler | |
| 153 | +| Use Case | Authentication, global request validation | Detailed error handling, custom error messages | |
| 154 | +| Custom Error Responses | Limited, generalized JSON responses | Structured, frontend-compatible JSON responses | |
| 155 | +| Custom Error Classes | ❌ | ✅ | |
| 156 | +| Error Logging Integration | ❌ | ✅ (supports Sentry, Datadog, etc.) | |
| 157 | +| Fine-Grained Control | ❌ | ✅ | |
| 158 | +| Preventing Information Leakage | Limited, as it handles errors globally without distinguishing between error types | Enhanced, distinguishes between custom and unexpected errors to prevent sensitive data exposure | |
| 159 | +| Integration with Route Handlers | Middleware runs before route handlers, cannot modify responses within handlers | Wraps individual route handlers, allowing for customized responses per route | |
| 160 | +| Extensibility | Limited to what middleware can handle globally | Highly extensible through custom error classes and configurable options | |
| 161 | +
|
| 162 | +### Why Use Both Approaches Together |
| 163 | +
|
| 164 | +Combining both Next.js middleware and nextjs-centralized-error-handler provides a comprehensive error-handling strategy: |
| 165 | +
|
| 166 | +**Global Request Validation and Authentication:** |
| 167 | +
|
| 168 | +- Use Next.js middleware to handle tasks that need to be applied across multiple routes, such as authentication, authorization, and general request validation. |
| 169 | +
|
| 170 | +**Route-Specific Detailed Error Handling:** |
| 171 | +
|
| 172 | +- Use nextjs-centralized-error-handler to manage errors that occur within individual route handlers, allowing for customized and structured error responses tailored to each route's specific needs. |
| 173 | +
|
| 174 | +### Example: Using Both Middleware and nextjs-centralized-error-handler |
| 175 | +
|
| 176 | +#### Middleware (middleware.js): |
| 177 | +
|
| 178 | +```javascript |
| 179 | +// middleware.js (Next.js Middleware for global authentication) |
| 180 | +import { NextResponse } from 'next/server'; |
| 181 | +
|
| 182 | +export function middleware(req) { |
| 183 | + // Example of authentication |
| 184 | + if (!req.headers.get('Authorization')) { |
| 185 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); |
| 186 | + } |
| 187 | +
|
| 188 | + return NextResponse.next(); // Continue to the route handler |
| 189 | +} |
| 190 | +
|
| 191 | +export const config = { |
| 192 | + matcher: '/api/:path*', // Applies middleware only to /api/* routes |
| 193 | +}; |
| 194 | +``` |
| 195 | +
|
| 196 | +#### Route Handler (pages/api/example.js): |
| 197 | +
|
| 198 | +```javascript |
| 199 | +// pages/api/example.js (Using nextjs-centralized-error-handler for route-specific errors) |
| 200 | +const { errorHandler, BadRequestError } = require('nextjs-centralized-error-handler'); |
| 201 | +
|
| 202 | +const handler = async (req, res) => { |
| 203 | + if (!req.body.name) { |
| 204 | + throw new BadRequestError('Name is required.'); |
| 205 | + } |
| 206 | +
|
| 207 | + // POST request handling logic |
| 208 | + res.status(200).json({ message: 'Success' }); |
| 209 | +}; |
| 210 | +
|
| 211 | +export default errorHandler(handler); |
| 212 | +``` |
| 213 | +
|
| 214 | +### Explanation: |
| 215 | +
|
| 216 | +- **Middleware (middleware.js):** |
| 217 | + - Handles global tasks like authentication. |
| 218 | + - Applies to all `/api/*` routes based on the matcher configuration. |
| 219 | +
|
| 220 | +- **Route Handler (example.js):** |
| 221 | + - Handles route-specific logic. |
| 222 | + - Utilizes `nextjs-centralized-error-handler` for detailed error handling and structured responses. |
| 223 | +
|
| 224 | +By using Next.js middleware for request-level checks and `nextjs-centralized-error-handler` for response-level error handling, you achieve both broad validation and fine-grained error management. |
| 225 | +
|
| 226 | +--- |
| 227 | +
|
118 | 228 | ### Key Advantages of `nextjs-centralized-error-handler`:
|
119 | 229 |
|
120 | 230 | - **Centralized error handling** through a higher-order function.
|
|
0 commit comments