Skip to content

Commit 59bcf57

Browse files
committed
docs: revised the readme for better clarity and examples
1 parent 65940d2 commit 59bcf57

File tree

2 files changed

+111
-1
lines changed

2 files changed

+111
-1
lines changed

README.md

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
- [Quick Start](#quick-start)
1616
- [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)
1718
- [Key Advantages of `nextjs-centralized-error-handler`](#key-advantages-of-nextjs-centralized-error-handler)
1819
- [Traditional Approach vs. `nextjs-centralized-error-handler`](#traditional-approach-vs-nextjs-centralized-error-handler)
1920
- [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
115116
116117
---
117118
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+
118228
### Key Advantages of `nextjs-centralized-error-handler`:
119229
120230
- **Centralized error handling** through a higher-order function.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "nextjs-centralized-error-handler",
3-
"version": "1.0.3",
3+
"version": "1.0.4",
44
"main": "index.js",
55
"scripts": {
66
"test": "jest",

0 commit comments

Comments
 (0)