You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
**A comprehensive, secure error-handling package designed specifically for Next.js applications.** While Next.js 13 provides global middleware for high-level request interception, `nextjs-centralized-error-handler` enables **fine-grained, route-level error handling** with custom error classes, ensuring that error responses are both consistent and structured. The package simplifies error handling by removing the need for repetitive `try-catch` blocks, enhancing security by preventing sensitive data leakage, and making error responses frontend-compatible. Fully compatible with Next.js 13 and above.
11
+
**A comprehensive, secure error-handling package designed specifically for Next.js applications.** While Next.js 13 provides global middleware for high-level request interception, `nextjs-centralized-error-handler` enables **fine-grained, route-level error handling** with `custom error classes`, ensuring that error responses are both consistent and structured. The package simplifies error handling by removing the need for repetitive `try-catch` blocks, enhancing security by preventing sensitive data leakage, and making error responses frontend-compatible. Fully compatible with Next.js 13 and above.
12
12
13
13
## Table of Contents
14
14
@@ -104,7 +104,7 @@ Next.js 13’s middleware offers powerful global interception capabilities, idea
104
104
105
105
1. **Route-Specific Error Management**: With `nextjs-centralized-error-handler`, each route can define its own contextual error handling, with tailored messages that match the route’s functionality. This modularity is essential for complex applications with varied error handling needs across different endpoints.
106
106
107
-
2. **Custom Error Classes with Detailed Responses**: The package introduces custom error classes (e.g., `BadRequestError`, `UnauthorizedError`) with structured, frontend-friendly JSON responses. These responses are enriched with metadata like status codes and error types, ensuring predictable and standardized error handling for backend and frontend teams.
107
+
2. **Custom Error Classes with Detailed Responses**: The package introduces `custom error classes` (e.g., `BadRequestError`, `UnauthorizedError`) with structured, frontend-friendly JSON responses. These responses are enriched with metadata like status codes and error types, ensuring predictable and standardized error handling for backend and frontend teams.
108
108
109
109
3. **Enhanced Security and Data Privacy**: Only errors that are intentional instances of `CustomError` have their status codes and messages sent to the client. For unexpected errors, a generic error message is used, and sensitive details are kept server-side, minimizing information leakage.
110
110
@@ -145,42 +145,106 @@ export const config = {
145
145
146
146
### Comparison with nextjs-centralized-error-handler
147
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:
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:
| 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
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 |
160
+
| Extensibility | Limited to what middleware can handle globally | Highly extensible through `custom error classes` and configurable options |
161
161
162
-
### Why Use Both Approaches Together
162
+
### Understanding Scope and Flexibility: Next.js Middleware vs. `nextjs-centralized-error-handler`
163
163
164
-
Combining both Next.js middleware and nextjs-centralized-error-handler provides a comprehensive error-handling strategy:
164
+
While Next.js middleware provides a powerful mechanism for high-level request interception, `nextjs-centralized-error-handler` excels at fine-grained errorhandling within individual API routes. This section clarifies their distinct roles and how they can be used together effectively.
165
165
166
-
**Global Request Validation and Authentication:**
166
+
#### Scenario: User Input Validation
167
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.
168
+
Imagine you are building an API route that requires a user's name to be provided in the request body. If the name is missing, you want to respond with a clear and specific error message. Let's see how each approach handles this scenario.
169
169
170
-
**Route-Specific Detailed Error Handling:**
170
+
##### Using Next.js Middleware
171
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.
172
+
In Next.js, middleware can be used to validate requests globally. However, it cannot catch exceptions thrown within individual route handlers.
173
173
174
-
### Example: Using Both Middleware and nextjs-centralized-error-handler
174
+
```javascript
175
+
// middleware.js
176
+
import { NextResponse } from 'next/server';
177
+
178
+
exportfunctionmiddleware(req) {
179
+
try {
180
+
// You can include any logic here that might throw an error
181
+
returnNextResponse.next(); // Proceed to the route handler
182
+
} catch (error) {
183
+
// Handle the error and return an appropriate response
184
+
return NextResponse.json({ error: 'An error occurred while processing your request.' }, { status: 500 });
185
+
}
186
+
}
187
+
```
188
+
```javascript
189
+
// pages/api/example.js
190
+
const handler = async (req, res) => {
191
+
if (!req.body.name) {
192
+
throw new Error('Name is required.'); // This will not be caught by middleware
1. The `errorHandler` wraps the route handler, intercepting any errors thrown within it.
229
+
2. If `req.body.name` is missing, the `BadRequestError` is thrown and caught by `errorHandler`.
230
+
3. This results in a structured response with the appropriate status code (400) and a clear error message ("Name is required.").
231
+
232
+
#### Why Use Both Approaches Together
233
+
234
+
Combining both Next.js middleware and `nextjs-centralized-error-handler` provides a comprehensive error-handling strategy:
235
+
236
+
- **Global Request Validation and Authentication:** Use Next.js middleware to handle tasks that need to be applied across multiple routes, such as authentication, authorization, and general request validation.
237
+
- **Route-Specific Detailed Error Handling:** 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.
238
+
239
+
##### Example: Using Both Middleware and `nextjs-centralized-error-handler`
240
+
241
+
**Middleware (middleware.js):**
177
242
178
243
```javascript
179
244
// middleware.js (Next.js Middleware for global authentication)
- Applies to all `/api/*` routes based on the matcher configuration.
277
+
**Explanation:**
219
278
220
-
- **Route Handler (example.js):**
221
-
- Handles route-specific logic.
222
-
- Utilizes `nextjs-centralized-error-handler` for detailed error handling and structured responses.
279
+
- **Middleware (middleware.js):** Handles global tasks like authentication. Applies to all `/api/*` routes based on the matcher configuration.
280
+
- **Route Handler (example.js):** Handles route-specific logic. Utilizes `nextjs-centralized-error-handler` for detailed error handling and structured responses.
223
281
224
282
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.
With `nextjs-centralized-error-handler`, you avoid repetitive error-handling code in each route. Instead, custom error classes and the `errorHandler` higher-order function provide centralized, consistent error responses, simplifying maintenance and extending error handling across the entire application.
341
+
With `nextjs-centralized-error-handler`, you avoid repetitive error-handling code in each route. Instead, `custom error classes` and the `errorHandler` higher-order function provide centralized, consistent error responses, simplifying maintenance and extending error handling across the entire application.
To address specific needs beyond predefined classes, the package is designed to be extensible, allowing you to create unique custom errors for advanced use cases. You can extend the base CustomError class to define your own error types, tailored to specific business logic. Here are some examples of custom errors you might create:
446
+
To address specific needs beyond predefined classes, the package is designed to be extensible, allowing you to create unique custom errors for advanced use cases. You can extend the base `CustomError class` to define your own error types, tailored to specific business logic. Here are some examples of custom errors you might create:
0 commit comments