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
|`v13.0.0`| Middleware can modify request headers, response headers, and send responses |
13
14
|`v12.2.0`| Middleware is stable |
14
15
|`v12.0.9`| Enforce absolute URLs in Edge Runtime ([PR](https://github.com/vercel/next.js/pull/33410)) |
@@ -220,18 +221,7 @@ export function middleware(request: NextRequest) {
220
221
221
222
## Producing a Response
222
223
223
-
You can respond to middleware directly by returning a `NextResponse` (responding from middleware is available since Next.js v13.0.0).
224
-
225
-
To enable middleware responses, update `next.config.js`:
226
-
227
-
```js
228
-
// next.config.js
229
-
module.exports= {
230
-
experimental: {
231
-
allowMiddlewareResponseBody:true,
232
-
},
233
-
}
234
-
```
224
+
You can respond to middleware directly by returning a `NextResponse` (responding from middleware is available since Next.js v13.1.0).
235
225
236
226
Once enabled, you can provide a response from middleware using the `Response` or `NextResponse` API:
237
227
@@ -257,6 +247,66 @@ export function middleware(request: NextRequest) {
257
247
}
258
248
```
259
249
250
+
## Advanced Middleware Flags
251
+
252
+
In `v13.1` of Next.js two additional flags were introduced for middleware, `skipMiddlewareUrlNormalize` and `skipTrailingSlashRedirect` to handle advanced use cases.
253
+
254
+
`skipTrailingSlashRedirect` allows disabling Next.js default redirects for adding or removing trailing slashes allowing custom handling inside middleware which can allow maintaining the trailing slash for some paths but not others allowing easier incremental migrations.
255
+
256
+
```js
257
+
// next.config.js
258
+
module.exports= {
259
+
skipTrailingSlashRedirect:true,
260
+
}
261
+
```
262
+
263
+
```js
264
+
// middleware.js
265
+
266
+
constlegacyPrefixes= ['/docs', '/blog']
267
+
268
+
exportdefaultasyncfunctionmiddleware(req) {
269
+
const { pathname } =req.nextUrl
270
+
271
+
if (legacyPrefixes.some((prefix) =>pathname.startsWith(prefix))) {
`skipMiddlewareUrlNormalize` allows disabling the URL normalizing Next.js does to make handling direct visits and client-transitions the same. There are some advanced cases where you need full control using the original URL which this unlocks.
287
+
288
+
```js
289
+
// next.config.js
290
+
291
+
module.exports= {
292
+
skipMiddlewareUrlNormalize:true,
293
+
}
294
+
```
295
+
296
+
```js
297
+
// middleware.js
298
+
299
+
exportdefaultasyncfunctionmiddleware(req) {
300
+
const { pathname } =req.nextUrl
301
+
302
+
// GET /_next/data/build-id/hello.json
303
+
304
+
console.log(pathname)
305
+
// with the flag this now /_next/data/build-id/hello.json
306
+
// without the flag this would be normalized to /hello
0 commit comments