2021-11-30 21:43:40 +01:00
|
|
|
import type { NextMiddleware, RequestData, FetchEventResult } from './types'
|
2021-12-13 19:30:24 +01:00
|
|
|
import type { RequestInit } from './spec-extension/request'
|
2021-10-26 00:59:41 +02:00
|
|
|
import { DeprecationError } from './error'
|
2021-10-20 19:52:11 +02:00
|
|
|
import { fromNodeHeaders } from './utils'
|
|
|
|
import { NextFetchEvent } from './spec-extension/fetch-event'
|
2021-12-13 19:30:24 +01:00
|
|
|
import { NextRequest } from './spec-extension/request'
|
2021-10-20 19:52:11 +02:00
|
|
|
import { NextResponse } from './spec-extension/response'
|
2021-10-26 00:59:41 +02:00
|
|
|
import { waitUntilSymbol } from './spec-compliant/fetch-event'
|
2022-05-27 20:29:04 +02:00
|
|
|
import { NextURL } from './next-url'
|
2021-10-20 19:52:11 +02:00
|
|
|
|
|
|
|
export async function adapter(params: {
|
2021-11-30 21:43:40 +01:00
|
|
|
handler: NextMiddleware
|
2021-10-26 17:03:39 +02:00
|
|
|
page: string
|
2021-10-20 19:52:11 +02:00
|
|
|
request: RequestData
|
|
|
|
}): Promise<FetchEventResult> {
|
2021-10-26 17:03:39 +02:00
|
|
|
const request = new NextRequestHint({
|
|
|
|
page: params.page,
|
2021-12-13 19:30:24 +01:00
|
|
|
input: params.request.url,
|
2021-10-26 17:03:39 +02:00
|
|
|
init: {
|
2022-02-18 20:43:43 +01:00
|
|
|
body: params.request.body,
|
2021-10-26 17:03:39 +02:00
|
|
|
geo: params.request.geo,
|
|
|
|
headers: fromNodeHeaders(params.request.headers),
|
|
|
|
ip: params.request.ip,
|
|
|
|
method: params.request.method,
|
|
|
|
nextConfig: params.request.nextConfig,
|
|
|
|
page: params.request.page,
|
|
|
|
},
|
2021-10-26 00:59:41 +02:00
|
|
|
})
|
2021-10-20 19:52:11 +02:00
|
|
|
|
2021-10-26 17:03:39 +02:00
|
|
|
const event = new NextFetchEvent({ request, page: params.page })
|
feat(middleware)!: forbids middleware response body (#36835)
_Hello Next.js team! First PR here, I hope I've followed the right practices._
### What's in there?
It has been decided to only support the following uses cases in Next.js' middleware:
- rewrite the URL (`x-middleware-rewrite` response header)
- redirect to another URL (`Location` response header)
- pass on to the next piece in the request pipeline (`x-middleware-next` response header)
1. during development, a warning on console tells developers when they are returning a response (either with `Response` or `NextResponse`).
2. at build time, this warning becomes an error.
3. at run time, returning a response body will trigger a 500 HTTP error with a JSON payload containing the detailed error.
All returned/thrown errors contain a link to the documentation.
This is a breaking feature compared to the _beta_ middleware implementation, and also removes `NextResponse.json()` which makes no sense any more.
### How to try it?
- runtime behavior: `HEADLESS=true yarn jest test/integration/middleware/core`
- build behavior : `yarn jest test/integration/middleware/build-errors`
- development behavior: `HEADLESS=true yarn jest test/development/middleware-warnings`
### Notes to reviewers
The limitation happens in next's web adapter. ~The initial implementation was to check `response.body` existence, but it turns out [`Response.redirect()`](https://github.com/vercel/next.js/blob/canary/packages/next/server/web/spec-compliant/response.ts#L42-L53) may set the response body (https://github.com/vercel/next.js/pull/31886). Hence why the proposed implementation specifically looks at response headers.~
`Response.redirect()` and `NextResponse.redirect()` do not need to include the final location in their body: it is handled by next server https://github.com/vercel/next.js/blob/canary/packages/next/server/next-server.ts#L1142
Because this is a breaking change, I had to adjust several tests cases, previously returning JSON/stream/text bodies. When relevant, these middlewares are returning data using response headers.
About DevEx: relying on AST analysis to detect forbidden use cases is not as good as running the code.
Such cases are easy to detect:
```js
new Response('a text value')
new Response(JSON.stringify({ /* whatever */ })
```
But these are false-positive cases:
```js
function returnNull() { return null }
new Response(returnNull())
function doesNothing() {}
new Response(doesNothing())
```
However, I see no good reasons to let users ship middleware such as the one above, hence why the build will fail, even if _technically speaking_, they are not setting the response body.
## Feature
- [x] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [x] Errors have helpful link attached, see `contributing.md`
## Documentation / Examples
- [x] Make sure the linting passes by running `yarn lint`
2022-05-20 00:02:20 +02:00
|
|
|
const response = await params.handler(request, event)
|
2021-10-20 19:52:11 +02:00
|
|
|
|
2022-05-27 20:29:04 +02:00
|
|
|
/**
|
|
|
|
* For rewrites we must always include the locale in the final pathname
|
|
|
|
* so we re-create the NextURL forcing it to include it when the it is
|
|
|
|
* an internal rewrite.
|
|
|
|
*/
|
|
|
|
if (response?.headers.has('x-middleware-rewrite')) {
|
|
|
|
const url = new NextURL(response.headers.get('x-middleware-rewrite')!, {
|
|
|
|
forceLocale: true,
|
|
|
|
headers: params.request.headers,
|
|
|
|
nextConfig: params.request.nextConfig,
|
|
|
|
})
|
|
|
|
|
|
|
|
if (url.host === request.nextUrl.host) {
|
|
|
|
response.headers.set(
|
|
|
|
'x-middleware-rewrite',
|
|
|
|
String(
|
|
|
|
new NextURL(response.headers.get('x-middleware-rewrite')!, {
|
|
|
|
forceLocale: true,
|
|
|
|
headers: params.request.headers,
|
|
|
|
nextConfig: params.request.nextConfig,
|
|
|
|
})
|
|
|
|
)
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-20 19:52:11 +02:00
|
|
|
return {
|
feat(middleware)!: forbids middleware response body (#36835)
_Hello Next.js team! First PR here, I hope I've followed the right practices._
### What's in there?
It has been decided to only support the following uses cases in Next.js' middleware:
- rewrite the URL (`x-middleware-rewrite` response header)
- redirect to another URL (`Location` response header)
- pass on to the next piece in the request pipeline (`x-middleware-next` response header)
1. during development, a warning on console tells developers when they are returning a response (either with `Response` or `NextResponse`).
2. at build time, this warning becomes an error.
3. at run time, returning a response body will trigger a 500 HTTP error with a JSON payload containing the detailed error.
All returned/thrown errors contain a link to the documentation.
This is a breaking feature compared to the _beta_ middleware implementation, and also removes `NextResponse.json()` which makes no sense any more.
### How to try it?
- runtime behavior: `HEADLESS=true yarn jest test/integration/middleware/core`
- build behavior : `yarn jest test/integration/middleware/build-errors`
- development behavior: `HEADLESS=true yarn jest test/development/middleware-warnings`
### Notes to reviewers
The limitation happens in next's web adapter. ~The initial implementation was to check `response.body` existence, but it turns out [`Response.redirect()`](https://github.com/vercel/next.js/blob/canary/packages/next/server/web/spec-compliant/response.ts#L42-L53) may set the response body (https://github.com/vercel/next.js/pull/31886). Hence why the proposed implementation specifically looks at response headers.~
`Response.redirect()` and `NextResponse.redirect()` do not need to include the final location in their body: it is handled by next server https://github.com/vercel/next.js/blob/canary/packages/next/server/next-server.ts#L1142
Because this is a breaking change, I had to adjust several tests cases, previously returning JSON/stream/text bodies. When relevant, these middlewares are returning data using response headers.
About DevEx: relying on AST analysis to detect forbidden use cases is not as good as running the code.
Such cases are easy to detect:
```js
new Response('a text value')
new Response(JSON.stringify({ /* whatever */ })
```
But these are false-positive cases:
```js
function returnNull() { return null }
new Response(returnNull())
function doesNothing() {}
new Response(doesNothing())
```
However, I see no good reasons to let users ship middleware such as the one above, hence why the build will fail, even if _technically speaking_, they are not setting the response body.
## Feature
- [x] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [x] Errors have helpful link attached, see `contributing.md`
## Documentation / Examples
- [x] Make sure the linting passes by running `yarn lint`
2022-05-20 00:02:20 +02:00
|
|
|
response: response || NextResponse.next(),
|
2021-10-20 19:52:11 +02:00
|
|
|
waitUntil: Promise.all(event[waitUntilSymbol]),
|
|
|
|
}
|
|
|
|
}
|
2021-10-26 00:59:41 +02:00
|
|
|
|
feat(middleware)!: forbids middleware response body (#36835)
_Hello Next.js team! First PR here, I hope I've followed the right practices._
### What's in there?
It has been decided to only support the following uses cases in Next.js' middleware:
- rewrite the URL (`x-middleware-rewrite` response header)
- redirect to another URL (`Location` response header)
- pass on to the next piece in the request pipeline (`x-middleware-next` response header)
1. during development, a warning on console tells developers when they are returning a response (either with `Response` or `NextResponse`).
2. at build time, this warning becomes an error.
3. at run time, returning a response body will trigger a 500 HTTP error with a JSON payload containing the detailed error.
All returned/thrown errors contain a link to the documentation.
This is a breaking feature compared to the _beta_ middleware implementation, and also removes `NextResponse.json()` which makes no sense any more.
### How to try it?
- runtime behavior: `HEADLESS=true yarn jest test/integration/middleware/core`
- build behavior : `yarn jest test/integration/middleware/build-errors`
- development behavior: `HEADLESS=true yarn jest test/development/middleware-warnings`
### Notes to reviewers
The limitation happens in next's web adapter. ~The initial implementation was to check `response.body` existence, but it turns out [`Response.redirect()`](https://github.com/vercel/next.js/blob/canary/packages/next/server/web/spec-compliant/response.ts#L42-L53) may set the response body (https://github.com/vercel/next.js/pull/31886). Hence why the proposed implementation specifically looks at response headers.~
`Response.redirect()` and `NextResponse.redirect()` do not need to include the final location in their body: it is handled by next server https://github.com/vercel/next.js/blob/canary/packages/next/server/next-server.ts#L1142
Because this is a breaking change, I had to adjust several tests cases, previously returning JSON/stream/text bodies. When relevant, these middlewares are returning data using response headers.
About DevEx: relying on AST analysis to detect forbidden use cases is not as good as running the code.
Such cases are easy to detect:
```js
new Response('a text value')
new Response(JSON.stringify({ /* whatever */ })
```
But these are false-positive cases:
```js
function returnNull() { return null }
new Response(returnNull())
function doesNothing() {}
new Response(doesNothing())
```
However, I see no good reasons to let users ship middleware such as the one above, hence why the build will fail, even if _technically speaking_, they are not setting the response body.
## Feature
- [x] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [x] Errors have helpful link attached, see `contributing.md`
## Documentation / Examples
- [x] Make sure the linting passes by running `yarn lint`
2022-05-20 00:02:20 +02:00
|
|
|
export function blockUnallowedResponse(
|
|
|
|
promise: Promise<FetchEventResult>
|
|
|
|
): Promise<FetchEventResult> {
|
|
|
|
return promise.then((result) => {
|
|
|
|
if (result.response?.body) {
|
|
|
|
console.error(
|
|
|
|
new Error(
|
|
|
|
`A middleware can not alter response's body. Learn more: https://nextjs.org/docs/messages/returning-response-body-in-middleware`
|
|
|
|
)
|
|
|
|
)
|
|
|
|
return {
|
|
|
|
...result,
|
|
|
|
response: new Response('Internal Server Error', {
|
|
|
|
status: 500,
|
|
|
|
statusText: 'Internal Server Error',
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-10-26 00:59:41 +02:00
|
|
|
class NextRequestHint extends NextRequest {
|
2021-10-26 17:03:39 +02:00
|
|
|
sourcePage: string
|
|
|
|
|
|
|
|
constructor(params: {
|
|
|
|
init: RequestInit
|
|
|
|
input: Request | string
|
|
|
|
page: string
|
|
|
|
}) {
|
|
|
|
super(params.input, params.init)
|
|
|
|
this.sourcePage = params.page
|
2021-10-26 00:59:41 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
get request() {
|
2021-10-26 17:03:39 +02:00
|
|
|
throw new DeprecationError({ page: this.sourcePage })
|
2021-10-26 00:59:41 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
respondWith() {
|
2021-10-26 17:03:39 +02:00
|
|
|
throw new DeprecationError({ page: this.sourcePage })
|
2021-10-26 00:59:41 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
waitUntil() {
|
2021-10-26 17:03:39 +02:00
|
|
|
throw new DeprecationError({ page: this.sourcePage })
|
2021-10-26 00:59:41 +02:00
|
|
|
}
|
|
|
|
}
|