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
@@ -125,6 +126,7 @@ Next.js 13 middleware can be defined globally and applied across all routes that
125
126
126
127
```javascript
127
128
// middleware.js (placed at the root of the app)
129
+
128
130
import { NextResponse } from 'next/server';
129
131
130
132
exportfunctionmiddleware(req) {
@@ -172,6 +174,7 @@ In Next.js, middleware can be used to validate requests globally. However, it ca
172
174
173
175
```javascript
174
176
// middleware.js
177
+
175
178
import { NextResponse } from 'next/server';
176
179
177
180
exportfunctionmiddleware(req) {
@@ -186,6 +189,7 @@ export function middleware(req) {
186
189
```
187
190
```javascript
188
191
// pages/api/example.js
192
+
189
193
const handler = async (req, res) => {
190
194
if (!req.body.name) {
191
195
throw new Error('Name is required.'); // This will not be caught by middleware
@@ -203,12 +207,13 @@ export default handler;
203
207
2. If `req.body.name` is missing, the `Error` is thrown.
204
208
3. However, the middleware will not catch this error, resulting in a generic 500 Internal Server Error.
205
209
206
-
##### Using nextjs-centralized-error-handler
210
+
#### Using `nextjs-centralized-error-handler`
207
211
208
212
In contrast, `nextjs-centralized-error-handler` provides a higher-order functionthat captures errors thrown in route handlers.
209
213
210
214
```javascript
211
215
// pages/api/example.js
216
+
212
217
import { errorHandler, BadRequestError } from 'nextjs-centralized-error-handler';
213
218
214
219
const handler = async (req, res) => {
@@ -235,12 +240,13 @@ Combining both Next.js middleware and `nextjs-centralized-error-handler` provide
235
240
- **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.
236
241
- **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.
237
242
238
-
##### Example: Using Both Middleware and `nextjs-centralized-error-handler`
243
+
### Example: Using Both Middleware and `nextjs-centralized-error-handler`
239
244
240
245
**Middleware (middleware.js):**
241
246
242
247
```javascript
243
248
// middleware.js (Next.js Middleware for global authentication)
249
+
244
250
import { NextResponse } from 'next/server';
245
251
246
252
export function middleware(req) {
@@ -260,6 +266,7 @@ export const config = {
260
266
261
267
```javascript
262
268
// pages/api/example.js (Using nextjs-centralized-error-handler for route-specific errors)
0 commit comments