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'
|
2022-06-09 13:10:21 +02:00
|
|
|
import { PageSignatureError } 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'
|
2022-06-08 17:41:28 +02:00
|
|
|
import { relativizeURL } from '../../shared/lib/router/utils/relativize-url'
|
2022-05-30 14:01:36 +02:00
|
|
|
import { waitUntilSymbol } from './spec-extension/fetch-event'
|
2022-05-27 20:29:04 +02:00
|
|
|
import { NextURL } from './next-url'
|
2022-09-15 16:53:51 +02:00
|
|
|
import { stripInternalSearchParams } from '../internal-utils'
|
2022-10-12 09:17:17 +02:00
|
|
|
import { normalizeRscPath } from '../../shared/lib/router/utils/app-paths'
|
2022-11-08 01:35:32 +01:00
|
|
|
import {
|
|
|
|
NEXT_ROUTER_PREFETCH,
|
|
|
|
NEXT_ROUTER_STATE_TREE,
|
|
|
|
RSC,
|
|
|
|
} from '../../client/components/app-router-headers'
|
2021-10-20 19:52:11 +02:00
|
|
|
|
2022-08-11 23:32:52 +02:00
|
|
|
class NextRequestHint extends NextRequest {
|
|
|
|
sourcePage: string
|
|
|
|
|
|
|
|
constructor(params: {
|
|
|
|
init: RequestInit
|
|
|
|
input: Request | string
|
|
|
|
page: string
|
|
|
|
}) {
|
|
|
|
super(params.input, params.init)
|
|
|
|
this.sourcePage = params.page
|
|
|
|
}
|
|
|
|
|
|
|
|
get request() {
|
|
|
|
throw new PageSignatureError({ page: this.sourcePage })
|
|
|
|
}
|
|
|
|
|
|
|
|
respondWith() {
|
|
|
|
throw new PageSignatureError({ page: this.sourcePage })
|
|
|
|
}
|
|
|
|
|
|
|
|
waitUntil() {
|
|
|
|
throw new PageSignatureError({ page: this.sourcePage })
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-21 15:47:31 +02:00
|
|
|
const FLIGHT_PARAMETERS = [
|
2022-11-08 01:35:32 +01:00
|
|
|
[RSC],
|
|
|
|
[NEXT_ROUTER_STATE_TREE],
|
|
|
|
[NEXT_ROUTER_PREFETCH],
|
2022-09-21 15:47:31 +02:00
|
|
|
] as const
|
|
|
|
|
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> {
|
2022-09-15 16:53:51 +02:00
|
|
|
// TODO-APP: use explicit marker for this
|
|
|
|
const isEdgeRendering = typeof self.__BUILD_MANIFEST !== 'undefined'
|
|
|
|
|
2022-10-12 09:17:17 +02:00
|
|
|
params.request.url = normalizeRscPath(params.request.url, true)
|
|
|
|
|
2022-06-08 17:41:28 +02:00
|
|
|
const requestUrl = new NextURL(params.request.url, {
|
|
|
|
headers: params.request.headers,
|
|
|
|
nextConfig: params.request.nextConfig,
|
|
|
|
})
|
|
|
|
|
|
|
|
// Ensure users only see page requests, never data requests.
|
|
|
|
const buildId = requestUrl.buildId
|
|
|
|
requestUrl.buildId = ''
|
|
|
|
|
2022-06-10 19:35:12 +02:00
|
|
|
const isDataReq = params.request.headers['x-nextjs-data']
|
|
|
|
|
2022-06-20 13:31:19 +02:00
|
|
|
if (isDataReq && requestUrl.pathname === '/index') {
|
|
|
|
requestUrl.pathname = '/'
|
|
|
|
}
|
|
|
|
|
2022-09-21 15:47:31 +02:00
|
|
|
const requestHeaders = fromNodeHeaders(params.request.headers)
|
2022-09-15 16:53:51 +02:00
|
|
|
// Parameters should only be stripped for middleware
|
|
|
|
if (!isEdgeRendering) {
|
2022-09-21 15:47:31 +02:00
|
|
|
for (const param of FLIGHT_PARAMETERS) {
|
2022-11-08 01:35:32 +01:00
|
|
|
requestHeaders.delete(param.toString().toLowerCase())
|
2022-09-21 15:47:31 +02:00
|
|
|
}
|
2022-06-10 19:35:12 +02:00
|
|
|
}
|
|
|
|
|
2022-09-15 16:53:51 +02:00
|
|
|
// Strip internal query parameters off the request.
|
|
|
|
stripInternalSearchParams(requestUrl.searchParams, true)
|
|
|
|
|
2021-10-26 17:03:39 +02:00
|
|
|
const request = new NextRequestHint({
|
|
|
|
page: params.page,
|
2022-06-08 17:41:28 +02:00
|
|
|
input: String(requestUrl),
|
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,
|
2022-09-21 15:47:31 +02:00
|
|
|
headers: requestHeaders,
|
2021-10-26 17:03:39 +02:00
|
|
|
ip: params.request.ip,
|
|
|
|
method: params.request.method,
|
|
|
|
nextConfig: params.request.nextConfig,
|
|
|
|
},
|
2021-10-26 00:59:41 +02:00
|
|
|
})
|
2021-10-20 19:52:11 +02:00
|
|
|
|
2022-06-08 17:41:28 +02:00
|
|
|
/**
|
|
|
|
* This allows to identify the request as a data request. The user doesn't
|
|
|
|
* need to know about this property neither use it. We add it for testing
|
|
|
|
* purposes.
|
|
|
|
*/
|
2022-06-10 19:35:12 +02:00
|
|
|
if (isDataReq) {
|
2022-06-08 17:41:28 +02:00
|
|
|
Object.defineProperty(request, '__isData', {
|
|
|
|
enumerable: false,
|
|
|
|
value: true,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-10-26 17:03:39 +02:00
|
|
|
const event = new NextFetchEvent({ request, page: params.page })
|
2022-06-08 17:41:28 +02:00
|
|
|
let response = await params.handler(request, event)
|
2021-10-20 19:52:11 +02:00
|
|
|
|
2022-10-12 14:02:25 +02:00
|
|
|
// check if response is a Response object
|
|
|
|
if (response && !(response instanceof Response)) {
|
|
|
|
throw new TypeError('Expected an instance of Response to be returned')
|
|
|
|
}
|
|
|
|
|
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
|
2022-06-08 17:41:28 +02:00
|
|
|
* an internal rewrite. Also we make sure the outgoing rewrite URL is
|
|
|
|
* a data URL if the request was a data request.
|
2022-05-27 20:29:04 +02:00
|
|
|
*/
|
2022-06-08 17:41:28 +02:00
|
|
|
const rewrite = response?.headers.get('x-middleware-rewrite')
|
|
|
|
if (response && rewrite) {
|
|
|
|
const rewriteUrl = new NextURL(rewrite, {
|
2022-05-27 20:29:04 +02:00
|
|
|
forceLocale: true,
|
|
|
|
headers: params.request.headers,
|
|
|
|
nextConfig: params.request.nextConfig,
|
|
|
|
})
|
|
|
|
|
2022-10-04 19:08:17 +02:00
|
|
|
if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {
|
|
|
|
if (rewriteUrl.host === request.nextUrl.host) {
|
|
|
|
rewriteUrl.buildId = buildId || rewriteUrl.buildId
|
|
|
|
response.headers.set('x-middleware-rewrite', String(rewriteUrl))
|
|
|
|
}
|
2022-06-08 17:41:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* When the request is a data request we must show if there was a rewrite
|
|
|
|
* with an internal header so the client knows which component to load
|
|
|
|
* from the data request.
|
|
|
|
*/
|
2022-06-10 19:35:12 +02:00
|
|
|
if (isDataReq) {
|
2022-06-08 17:41:28 +02:00
|
|
|
response.headers.set(
|
2022-06-15 16:09:51 +02:00
|
|
|
'x-nextjs-rewrite',
|
2022-06-08 17:41:28 +02:00
|
|
|
relativizeURL(String(rewriteUrl), String(requestUrl))
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* For redirects we will not include the locale in case when it is the
|
|
|
|
* default and we must also make sure the outgoing URL is a data one if
|
|
|
|
* the incoming request was a data request.
|
|
|
|
*/
|
|
|
|
const redirect = response?.headers.get('Location')
|
|
|
|
if (response && redirect) {
|
|
|
|
const redirectURL = new NextURL(redirect, {
|
|
|
|
forceLocale: false,
|
|
|
|
headers: params.request.headers,
|
|
|
|
nextConfig: params.request.nextConfig,
|
|
|
|
})
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Responses created from redirects have immutable headers so we have
|
|
|
|
* to clone the response to be able to modify it.
|
|
|
|
*/
|
|
|
|
response = new Response(response.body, response)
|
|
|
|
|
2022-10-04 19:08:17 +02:00
|
|
|
if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {
|
|
|
|
if (redirectURL.host === request.nextUrl.host) {
|
|
|
|
redirectURL.buildId = buildId || redirectURL.buildId
|
|
|
|
response.headers.set('Location', String(redirectURL))
|
|
|
|
}
|
2022-06-08 17:41:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* When the request is a data request we can't use the location header as
|
|
|
|
* it may end up with CORS error. Instead we map to an internal header so
|
|
|
|
* the client knows the destination.
|
|
|
|
*/
|
2022-06-10 19:35:12 +02:00
|
|
|
if (isDataReq) {
|
2022-06-08 17:41:28 +02:00
|
|
|
response.headers.delete('Location')
|
2022-05-27 20:29:04 +02:00
|
|
|
response.headers.set(
|
2022-06-08 17:41:28 +02:00
|
|
|
'x-nextjs-redirect',
|
|
|
|
relativizeURL(String(redirectURL), String(requestUrl))
|
2022-05-27 20:29:04 +02:00
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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> {
|
2022-10-10 21:58:18 +02:00
|
|
|
if (process.env.__NEXT_ALLOW_MIDDLEWARE_RESPONSE_BODY) {
|
|
|
|
return promise
|
|
|
|
}
|
|
|
|
|
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
|
|
|
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
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-08-15 16:29:51 +02:00
|
|
|
function getUnsupportedModuleErrorMessage(module: string) {
|
|
|
|
// warning: if you change these messages, you must adjust how react-dev-overlay's middleware detects modules not found
|
|
|
|
return `The edge runtime does not support Node.js '${module}' module.
|
|
|
|
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`
|
2022-07-20 16:53:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function __import_unsupported(moduleName: string) {
|
|
|
|
const proxy: any = new Proxy(function () {}, {
|
|
|
|
get(_obj, prop) {
|
|
|
|
if (prop === 'then') {
|
|
|
|
return {}
|
|
|
|
}
|
|
|
|
throw new Error(getUnsupportedModuleErrorMessage(moduleName))
|
|
|
|
},
|
|
|
|
construct() {
|
|
|
|
throw new Error(getUnsupportedModuleErrorMessage(moduleName))
|
|
|
|
},
|
|
|
|
apply(_target, _this, args) {
|
|
|
|
if (typeof args[0] === 'function') {
|
|
|
|
return args[0](proxy)
|
|
|
|
}
|
|
|
|
throw new Error(getUnsupportedModuleErrorMessage(moduleName))
|
|
|
|
},
|
|
|
|
})
|
|
|
|
return new Proxy({}, { get: () => proxy })
|
|
|
|
}
|
|
|
|
|
2022-08-15 16:29:51 +02:00
|
|
|
export function enhanceGlobals() {
|
|
|
|
// The condition is true when the "process" module is provided
|
|
|
|
if (process !== global.process) {
|
|
|
|
// prefer local process but global.process has correct "env"
|
|
|
|
process.env = global.process.env
|
|
|
|
global.process = process
|
|
|
|
}
|
|
|
|
|
|
|
|
// to allow building code that import but does not use node.js modules,
|
|
|
|
// webpack will expect this function to exist in global scope
|
|
|
|
Object.defineProperty(globalThis, '__import_unsupported', {
|
|
|
|
value: __import_unsupported,
|
|
|
|
enumerable: false,
|
|
|
|
configurable: false,
|
|
|
|
})
|
2022-07-20 16:53:27 +02:00
|
|
|
}
|