Unverified Commit 5d4ac47f authored by Lee Robinson's avatar Lee Robinson Committed by GitHub

Improve response body in Middleware error page. (#38537)

* Improve respond body in Middleware error page.

* Apply suggestions from code review
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent a2554c09
# Returning response body in middleware # Returning response body in Middleware
#### Why This Error Occurred #### Why This Error Occurred
Your [`middleware`](https://nextjs.org/docs/advanced-features/middleware) function returns a response body, which is not supported. [Middleware](https://nextjs.org/docs/advanced-features/middleware) can no longer produce a response body as of `v12.2+`.
Letting middleware respond to incoming requests would bypass Next.js routing mechanism, creating an unnecessary escape hatch.
#### Possible Ways to Fix It #### Possible Ways to Fix It
Next.js middleware gives you a great opportunity to run code and adjust to the requesting user. Migrate to using `rewrite`/`redirect` to Pages/API Routes handling a response.
It is intended for use cases like: #### Explanation
- A/B testing, where you **_rewrite_** to a different page based on external data (User agent, user location, a custom header or cookie...) To respect the differences in client-side and server-side navigation, and to help ensure that developers do not build insecure Middleware, Middleware can no longer produce a response body. This ensures that Middleware is only used to `rewrite`, `redirect`, or modify the incoming request (e.g. [setting cookies](https://nextjs.org/docs/advanced-features/middleware#using-cookies)).
```js The following patterns will no longer work:
export function middleware(req: NextRequest) {
let res = NextResponse.next()
// reuses cookie, or builds a new one.
const cookie = req.cookies.get(COOKIE_NAME) ?? buildABTestingCookie()
// the cookie contains the displayed variant, 0 being default ```js
const [, variantId] = cookie.split('.') new Response('a text value')
if (variantId !== '0') { new Response(streamOrBuffer)
const url = req.nextUrl.clone() new Response(JSON.stringify(obj), { headers: 'application/json' })
url.pathname = url.pathname.replace('/', `/${variantId}/`) NextResponse.json()
// rewrites the response to display desired variant ```
res = NextResponse.rewrite(url)
}
// don't forget to set cookie if not set yet ### How to upgrade
if (!req.cookies.has(COOKIE_NAME)) {
res.cookies.set(COOKIE_NAME, cookie)
}
return res
}
```
- authentication, where you **_redirect_** to your log-in/sign-in page any un-authenticated request For cases where Middleware is used to respond (such as authorization), you should migrate to use `rewrite`/`redirect` to pages that show an authorization error, login forms, or to an API Route.
```js #### Before
export function middleware(req: NextRequest) {
const basicAuth = req.headers.get('authorization')
if (basicAuth) { ```typescript
const auth = basicAuth.split(' ')[1] // pages/_middleware.ts
const [user, pwd] = atob(auth).split(':') import { NextResponse } from 'next/server'
if (areCredentialsValid(user, pwd)) { import type { NextRequest } from 'next/server'
return NextResponse.next() import { isAuthValid } from './lib/auth'
}
}
return NextResponse.redirect( export function middleware(request: NextRequest) {
new URL(`/login?from=${req.nextUrl.pathname}`, req.url) // Example function to validate auth
) if (isAuthValid(request)) {
}
```
- detecting bots and **_rewrite_** response to display to some sink
```js
export function middleware(req: NextRequest) {
if (isABotRequest(req)) {
// Bot detected! rewrite to the sink
const url = req.nextUrl.clone()
url.pathname = '/bot-detected'
return NextResponse.rewrite(url)
}
return NextResponse.next() return NextResponse.next()
} }
```
return NextResponse.json({ message: 'Auth required' }, { status: 401 })
- programmatically adding **_headers_** to the response, like cookies. }
```
```js
export function middleware(req: NextRequest) { #### After
const res = NextResponse.next(null, {
// sets a custom response header ```typescript
headers: { 'response-greetings': 'Hej!' }, // middleware.ts
}) import { NextResponse } from 'next/server'
// configures cookies import type { NextRequest } from 'next/server'
res.cookies.set('hello', 'world') import { isAuthValid } from './lib/auth'
return res
export function middleware(request: NextRequest) {
// Example function to validate auth
if (isAuthValid(request)) {
return NextResponse.next()
} }
```
request.nextUrl.searchParams.set('from', request.nextUrl.pathname)
request.nextUrl.pathname = '/login'
return NextResponse.redirect(request.nextUrl)
}
```
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment