Unverified Commit 9ee4c0cd authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Enable allowMiddlewareResponseBody by default (#44224)

Follow-up to #44195


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] 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`
- [ ] [e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 52fb820b
...@@ -221,18 +221,7 @@ export function middleware(request: NextRequest) { ...@@ -221,18 +221,7 @@ export function middleware(request: NextRequest) {
## Producing a Response ## Producing a Response
You can respond to middleware directly by returning a `NextResponse` (responding from middleware is available since Next.js v13.0.0). You can respond to middleware directly by returning a `NextResponse` (responding from middleware is available since Next.js v13.1.0).
To enable middleware responses, update `next.config.js`:
```js
// next.config.js
module.exports = {
experimental: {
allowMiddlewareResponseBody: true,
},
}
```
Once enabled, you can provide a response from middleware using the `Response` or `NextResponse` API: Once enabled, you can provide a response from middleware using the `Response` or `NextResponse` API:
......
...@@ -301,9 +301,6 @@ export function getDefineEnv({ ...@@ -301,9 +301,6 @@ export function getDefineEnv({
'process.env.__NEXT_I18N_SUPPORT': JSON.stringify(!!config.i18n), 'process.env.__NEXT_I18N_SUPPORT': JSON.stringify(!!config.i18n),
'process.env.__NEXT_I18N_DOMAINS': JSON.stringify(config.i18n?.domains), 'process.env.__NEXT_I18N_DOMAINS': JSON.stringify(config.i18n?.domains),
'process.env.__NEXT_ANALYTICS_ID': JSON.stringify(config.analyticsId), 'process.env.__NEXT_ANALYTICS_ID': JSON.stringify(config.analyticsId),
'process.env.__NEXT_ALLOW_MIDDLEWARE_RESPONSE_BODY': JSON.stringify(
config.allowMiddlewareResponseBody
),
'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE': JSON.stringify( 'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE': JSON.stringify(
config.skipMiddlewareUrlNormalize config.skipMiddlewareUrlNormalize
), ),
...@@ -2062,7 +2059,6 @@ export default async function getBaseWebpackConfig( ...@@ -2062,7 +2059,6 @@ export default async function getBaseWebpackConfig(
dev, dev,
sriEnabled: !dev && !!config.experimental.sri?.algorithm, sriEnabled: !dev && !!config.experimental.sri?.algorithm,
hasFontLoaders: !!config.experimental.fontLoaders, hasFontLoaders: !!config.experimental.fontLoaders,
allowMiddlewareResponseBody: !!config.allowMiddlewareResponseBody,
}), }),
isClient && isClient &&
new BuildManifestPlugin({ new BuildManifestPlugin({
...@@ -2154,10 +2150,6 @@ export default async function getBaseWebpackConfig( ...@@ -2154,10 +2150,6 @@ export default async function getBaseWebpackConfig(
['swcEmotion', !!config.compiler?.emotion], ['swcEmotion', !!config.compiler?.emotion],
['turbotrace', !!config.experimental.turbotrace], ['turbotrace', !!config.experimental.turbotrace],
['transpilePackages', !!config.transpilePackages], ['transpilePackages', !!config.transpilePackages],
[
'allowMiddlewareResponseBody',
!!config.allowMiddlewareResponseBody,
],
[ [
'skipMiddlewareUrlNormalize', 'skipMiddlewareUrlNormalize',
!!config.skipMiddlewareUrlNormalize, !!config.skipMiddlewareUrlNormalize,
......
...@@ -40,7 +40,7 @@ export default function middlewareLoader(this: any) { ...@@ -40,7 +40,7 @@ export default function middlewareLoader(this: any) {
buildInfo.rootDir = rootDir buildInfo.rootDir = rootDir
return ` return `
import { adapter, blockUnallowedResponse, enhanceGlobals } from 'next/dist/esm/server/web/adapter' import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
enhanceGlobals() enhanceGlobals()
...@@ -52,11 +52,11 @@ export default function middlewareLoader(this: any) { ...@@ -52,11 +52,11 @@ export default function middlewareLoader(this: any) {
} }
export default function (opts) { export default function (opts) {
return blockUnallowedResponse(adapter({ return adapter({
...opts, ...opts,
page: ${JSON.stringify(page)}, page: ${JSON.stringify(page)},
handler, handler,
})) })
} }
` `
} }
...@@ -232,21 +232,6 @@ function isInMiddlewareLayer(parser: webpack.javascript.JavascriptParser) { ...@@ -232,21 +232,6 @@ function isInMiddlewareLayer(parser: webpack.javascript.JavascriptParser) {
return parser.state.module?.layer === 'middleware' return parser.state.module?.layer === 'middleware'
} }
function isInMiddlewareFile(parser: webpack.javascript.JavascriptParser) {
return (
parser.state.current?.layer === 'middleware' &&
/middleware\.\w+$/.test(parser.state.current?.rawRequest)
)
}
function isNullLiteral(expr: any) {
return expr.value === null
}
function isUndefinedIdentifier(expr: any) {
return expr.name === 'undefined'
}
function isProcessEnvMemberExpression(memberExpression: any): boolean { function isProcessEnvMemberExpression(memberExpression: any): boolean {
return ( return (
memberExpression.object?.type === 'Identifier' && memberExpression.object?.type === 'Identifier' &&
...@@ -345,14 +330,12 @@ function getCodeAnalyzer(params: { ...@@ -345,14 +330,12 @@ function getCodeAnalyzer(params: {
dev: boolean dev: boolean
compiler: webpack.Compiler compiler: webpack.Compiler
compilation: webpack.Compilation compilation: webpack.Compilation
allowMiddlewareResponseBody: boolean
}) { }) {
return (parser: webpack.javascript.JavascriptParser) => { return (parser: webpack.javascript.JavascriptParser) => {
const { const {
dev, dev,
compiler: { webpack: wp }, compiler: { webpack: wp },
compilation, compilation,
allowMiddlewareResponseBody,
} = params } = params
const { hooks } = parser const { hooks } = parser
...@@ -488,32 +471,6 @@ function getCodeAnalyzer(params: { ...@@ -488,32 +471,6 @@ function getCodeAnalyzer(params: {
} }
} }
/**
* A handler for calls to `new Response()` so we can fail if user is setting the response's body.
*/
const handleNewResponseExpression = (node: any) => {
const firstParameter = node?.arguments?.[0]
if (
isInMiddlewareFile(parser) &&
firstParameter &&
!isNullLiteral(firstParameter) &&
!isUndefinedIdentifier(firstParameter)
) {
const error = buildWebpackError({
message: `Middleware is returning a response body (line: ${node.loc.start.line}), which is not supported.
Learn more: https://nextjs.org/docs/messages/returning-response-body-in-middleware`,
compilation,
parser,
...node,
})
if (dev) {
compilation.warnings.push(error)
} else {
compilation.errors.push(error)
}
}
}
/** /**
* Handler to store original source location of static and dynamic imports into module's buildInfo. * Handler to store original source location of static and dynamic imports into module's buildInfo.
*/ */
...@@ -568,10 +525,6 @@ Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`, ...@@ -568,10 +525,6 @@ Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`,
.tap(NAME, handleWrapWasmInstantiateExpression) .tap(NAME, handleWrapWasmInstantiateExpression)
} }
if (!allowMiddlewareResponseBody) {
hooks.new.for('Response').tap(NAME, handleNewResponseExpression)
hooks.new.for('NextResponse').tap(NAME, handleNewResponseExpression)
}
hooks.callMemberChain.for('process').tap(NAME, handleCallMemberChain) hooks.callMemberChain.for('process').tap(NAME, handleCallMemberChain)
hooks.expressionMemberChain.for('process').tap(NAME, handleCallMemberChain) hooks.expressionMemberChain.for('process').tap(NAME, handleCallMemberChain)
hooks.importCall.tap(NAME, handleImport) hooks.importCall.tap(NAME, handleImport)
...@@ -835,23 +788,19 @@ export default class MiddlewarePlugin { ...@@ -835,23 +788,19 @@ export default class MiddlewarePlugin {
private readonly dev: boolean private readonly dev: boolean
private readonly sriEnabled: boolean private readonly sriEnabled: boolean
private readonly hasFontLoaders: boolean private readonly hasFontLoaders: boolean
private readonly allowMiddlewareResponseBody: boolean
constructor({ constructor({
dev, dev,
sriEnabled, sriEnabled,
hasFontLoaders, hasFontLoaders,
allowMiddlewareResponseBody,
}: { }: {
dev: boolean dev: boolean
sriEnabled: boolean sriEnabled: boolean
hasFontLoaders: boolean hasFontLoaders: boolean
allowMiddlewareResponseBody: boolean
}) { }) {
this.dev = dev this.dev = dev
this.sriEnabled = sriEnabled this.sriEnabled = sriEnabled
this.hasFontLoaders = hasFontLoaders this.hasFontLoaders = hasFontLoaders
this.allowMiddlewareResponseBody = allowMiddlewareResponseBody
} }
public apply(compiler: webpack.Compiler) { public apply(compiler: webpack.Compiler) {
...@@ -864,7 +813,6 @@ export default class MiddlewarePlugin { ...@@ -864,7 +813,6 @@ export default class MiddlewarePlugin {
dev: this.dev, dev: this.dev,
compiler, compiler,
compilation, compilation,
allowMiddlewareResponseBody: this.allowMiddlewareResponseBody,
}) })
hooks.parser.for('javascript/auto').tap(NAME, codeAnalyzer) hooks.parser.for('javascript/auto').tap(NAME, codeAnalyzer)
hooks.parser.for('javascript/dynamic').tap(NAME, codeAnalyzer) hooks.parser.for('javascript/dynamic').tap(NAME, codeAnalyzer)
......
...@@ -38,7 +38,6 @@ export type Feature = ...@@ -38,7 +38,6 @@ export type Feature =
| `swc/target/${SWC_TARGET_TRIPLE}` | `swc/target/${SWC_TARGET_TRIPLE}`
| 'turbotrace' | 'turbotrace'
| 'transpilePackages' | 'transpilePackages'
| 'allowMiddlewareResponseBody'
| 'skipMiddlewareUrlNormalize' | 'skipMiddlewareUrlNormalize'
| 'skipTrailingSlashRedirect' | 'skipTrailingSlashRedirect'
...@@ -101,7 +100,6 @@ const BUILD_FEATURES: Array<Feature> = [ ...@@ -101,7 +100,6 @@ const BUILD_FEATURES: Array<Feature> = [
'swc/target/aarch64-pc-windows-msvc', 'swc/target/aarch64-pc-windows-msvc',
'turbotrace', 'turbotrace',
'transpilePackages', 'transpilePackages',
'allowMiddlewareResponseBody',
'skipMiddlewareUrlNormalize', 'skipMiddlewareUrlNormalize',
'skipTrailingSlashRedirect', 'skipTrailingSlashRedirect',
] ]
......
...@@ -7,9 +7,6 @@ const configSchema = { ...@@ -7,9 +7,6 @@ const configSchema = {
type: 'object', type: 'object',
additionalProperties: false, additionalProperties: false,
properties: { properties: {
allowMiddlewareResponseBody: {
type: 'boolean',
},
amp: { amp: {
additionalProperties: false, additionalProperties: false,
properties: { properties: {
......
...@@ -504,8 +504,6 @@ export interface NextConfig extends Record<string, any> { ...@@ -504,8 +504,6 @@ export interface NextConfig extends Record<string, any> {
// A list of packages that should always be transpiled and bundled in the server // A list of packages that should always be transpiled and bundled in the server
transpilePackages?: string[] transpilePackages?: string[]
allowMiddlewareResponseBody?: boolean
skipMiddlewareUrlNormalize?: boolean skipMiddlewareUrlNormalize?: boolean
skipTrailingSlashRedirect?: boolean skipTrailingSlashRedirect?: boolean
......
...@@ -615,18 +615,6 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) { ...@@ -615,18 +615,6 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) {
result.transpilePackages = (result.experimental as any).transpilePackages result.transpilePackages = (result.experimental as any).transpilePackages
} }
if (
result.experimental &&
'allowMiddlewareResponseBody' in (result.experimental as any)
) {
Log.warn(
`\`allowMiddlewareResponseBody\` has been moved out of \`experimental\`. Please update your ${configFileName} file accordingly.`
)
result.allowMiddlewareResponseBody = (
result.experimental as any
).allowMiddlewareResponseBody
}
if ( if (
result.experimental && result.experimental &&
'skipMiddlewareUrlNormalize' in (result.experimental as any) 'skipMiddlewareUrlNormalize' in (result.experimental as any)
......
...@@ -198,32 +198,6 @@ export async function adapter(params: { ...@@ -198,32 +198,6 @@ export async function adapter(params: {
} }
} }
export function blockUnallowedResponse(
promise: Promise<FetchEventResult>
): Promise<FetchEventResult> {
if (process.env.__NEXT_ALLOW_MIDDLEWARE_RESPONSE_BODY) {
return promise
}
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
})
}
function getUnsupportedModuleErrorMessage(module: string) { function getUnsupportedModuleErrorMessage(module: string) {
// warning: if you change these messages, you must adjust how react-dev-overlay's middleware detects modules not found // 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. return `The edge runtime does not support Node.js '${module}' module.
......
...@@ -167,7 +167,6 @@ export type EventBuildFeatureUsage = { ...@@ -167,7 +167,6 @@ export type EventBuildFeatureUsage = {
| 'build-lint' | 'build-lint'
| 'vercelImageGeneration' | 'vercelImageGeneration'
| 'transpilePackages' | 'transpilePackages'
| 'allowMiddlewareResponseBody'
| 'skipMiddlewareUrlNormalize' | 'skipMiddlewareUrlNormalize'
| 'skipTrailingSlashRedirect' | 'skipTrailingSlashRedirect'
invocationCount: number invocationCount: number
......
...@@ -61,9 +61,9 @@ describe('middlewares', () => { ...@@ -61,9 +61,9 @@ describe('middlewares', () => {
return new Response(await fetch('https://example.vercel.sh')); return new Response(await fetch('https://example.vercel.sh'));
}`, }`,
}, },
])('warns when $title', async ({ code }) => { ])('does not warn when $title', async ({ code }) => {
;({ cleanup } = await sandbox(next, new Map([[middlewarePath, code]]))) ;({ cleanup } = await sandbox(next, new Map([[middlewarePath, code]])))
expect(next.cliOutput).toMatch(middlewareWarning) expect(next.cliOutput).not.toMatch(middlewareWarning)
}) })
it.each([ it.each([
......
module.exports = { module.exports = {
allowMiddlewareResponseBody: true,
experimental: { experimental: {
appDir: true, appDir: true,
}, },
......
...@@ -29,25 +29,23 @@ describe('Middleware Responses', () => { ...@@ -29,25 +29,23 @@ describe('Middleware Responses', () => {
]) ])
}) })
it(`${label}should fail when returning a stream`, async () => { it(`${label}should not fail when returning a stream`, async () => {
const res = await fetchViaHTTP(next.url, `${locale}/stream-a-response`) const res = await fetchViaHTTP(next.url, `${locale}/stream-a-response`)
expect(res.status).toBe(500) expect(res.status).toBe(200)
if (!(global as any).isNextDeploy) { if (!(global as any).isNextDeploy) {
expect(await res.text()).toEqual('Internal Server Error') expect(next.cliOutput).not.toContain(
expect(next.cliOutput).toContain(
`A middleware can not alter response's body. Learn more: https://nextjs.org/docs/messages/returning-response-body-in-middleware` `A middleware can not alter response's body. Learn more: https://nextjs.org/docs/messages/returning-response-body-in-middleware`
) )
} }
}) })
it(`${label}should fail when returning a text body`, async () => { it(`${label}should not fail when returning a text body`, async () => {
const res = await fetchViaHTTP(next.url, `${locale}/send-response`) const res = await fetchViaHTTP(next.url, `${locale}/send-response`)
expect(res.status).toBe(500) expect(res.status).toBe(200)
if (!(global as any).isNextDeploy) { if (!(global as any).isNextDeploy) {
expect(await res.text()).toEqual('Internal Server Error') expect(next.cliOutput).not.toContain(
expect(next.cliOutput).toContain(
`A middleware can not alter response's body. Learn more: https://nextjs.org/docs/messages/returning-response-body-in-middleware` `A middleware can not alter response's body. Learn more: https://nextjs.org/docs/messages/returning-response-body-in-middleware`
) )
} }
......
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
allowMiddlewareResponseBody: true,
skipMiddlewareUrlNormalize: true, skipMiddlewareUrlNormalize: true,
skipTrailingSlashRedirect: true, skipTrailingSlashRedirect: true,
async redirects() { async redirects() {
......
...@@ -53,13 +53,13 @@ describe('Middleware validation during build', () => { ...@@ -53,13 +53,13 @@ describe('Middleware validation during build', () => {
])('given a middleware $title', ({ code }) => { ])('given a middleware $title', ({ code }) => {
beforeAll(() => writeFile(middlewareFile, code)) beforeAll(() => writeFile(middlewareFile, code))
it('throws an error', async () => { it('does not throw an error', async () => {
const { stderr, code } = await nextBuild(appDir, [], { const { stderr, code } = await nextBuild(appDir, [], {
stderr: true, stderr: true,
stdout: true, stdout: true,
}) })
expect(stderr).toMatch(middlewareError) expect(stderr).not.toMatch(middlewareError)
expect(code).toBe(1) expect(code).toBe(0)
}) })
}) })
......
module.exports = { module.exports = {
allowMiddlewareResponseBody: true,
skipMiddlewareUrlNormalize: true, skipMiddlewareUrlNormalize: true,
skipTrailingSlashRedirect: true, skipTrailingSlashRedirect: true,
} }
\ No newline at end of file
...@@ -1137,10 +1137,6 @@ describe('Telemetry CLI', () => { ...@@ -1137,10 +1137,6 @@ describe('Telemetry CLI', () => {
stderr, stderr,
'NEXT_BUILD_FEATURE_USAGE' 'NEXT_BUILD_FEATURE_USAGE'
) )
expect(featureUsageEvents).toContainEqual({
featureName: 'allowMiddlewareResponseBody',
invocationCount: 1,
})
expect(featureUsageEvents).toContainEqual({ expect(featureUsageEvents).toContainEqual({
featureName: 'skipMiddlewareUrlNormalize', featureName: 'skipMiddlewareUrlNormalize',
invocationCount: 1, invocationCount: 1,
......
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