Unverified Commit 67681fe0 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Replace middleware flag with warning (#30160)

Follow-up to https://github.com/vercel/next.js/pull/30154 this replaces the experimental flag with a warning that is shown once on usage instead. 
parent 7e81d13a
# Beta Middleware Used
#### Why This Error Occurred
The middleware feature of Next.js is still in beta so this warning is shown to express that the feature is not yet covered by semver and can experience changes at any point.
#### Possible Ways to Fix It
No fix necessary.
### Useful Links
- [semver documentation](https://semver.org/)
...@@ -4,6 +4,10 @@ ...@@ -4,6 +4,10 @@
"title": "Messages", "title": "Messages",
"heading": true, "heading": true,
"routes": [ "routes": [
{
"title": "beta-middleware",
"path": "/errors/beta-middleware.md"
},
{ {
"title": "custom-document-image-import", "title": "custom-document-image-import",
"path": "/errors/custom-document-image-import.md" "path": "/errors/custom-document-image-import.md"
......
...@@ -121,7 +121,7 @@ export function createEntrypoints( ...@@ -121,7 +121,7 @@ export function createEntrypoints(
const isLikeServerless = isTargetLikeServerless(target) const isLikeServerless = isTargetLikeServerless(target)
if (page.match(MIDDLEWARE_ROUTE) && config.experimental.middleware) { if (page.match(MIDDLEWARE_ROUTE)) {
const loaderOpts: MiddlewareLoaderOptions = { const loaderOpts: MiddlewareLoaderOptions = {
absolutePagePath: pages[page], absolutePagePath: pages[page],
page, page,
......
...@@ -285,13 +285,6 @@ export default async function build( ...@@ -285,13 +285,6 @@ export default async function build(
) )
const pageKeys = Object.keys(mappedPages) const pageKeys = Object.keys(mappedPages)
const hasMiddleware = pageKeys.some((page) => MIDDLEWARE_ROUTE.test(page)) const hasMiddleware = pageKeys.some((page) => MIDDLEWARE_ROUTE.test(page))
if (hasMiddleware && !config.experimental.middleware) {
console.warn(
`Warning: detected _middleware page but the "experimental.middleware" config was not enabled. Please enable it in ${config.configFileName}`
)
}
const conflictingPublicFiles: string[] = [] const conflictingPublicFiles: string[] = []
const hasCustomErrorPage: boolean = const hasCustomErrorPage: boolean =
mappedPages['/_error'].startsWith('private-next-pages') mappedPages['/_error'].startsWith('private-next-pages')
...@@ -300,6 +293,15 @@ export default async function build( ...@@ -300,6 +293,15 @@ export default async function build(
mappedPages['/404'].startsWith('private-next-pages') mappedPages['/404'].startsWith('private-next-pages')
) )
if (hasMiddleware) {
console.warn(
chalk.bold.yellow(`Warning: `) +
chalk.yellow(
`using beta Middleware (not covered by semver) - https://nextjs.org/docs/messages/beta-middleware`
)
)
}
if (hasPublicDir) { if (hasPublicDir) {
const hasPublicUnderScoreNextDir = await fileExists( const hasPublicUnderScoreNextDir = await fileExists(
path.join(publicDir, '_next') path.join(publicDir, '_next')
...@@ -1718,26 +1720,24 @@ export default async function build( ...@@ -1718,26 +1720,24 @@ export default async function build(
) )
} }
if (config.experimental.middleware) { const middlewareManifest: MiddlewareManifest = JSON.parse(
const middlewareManifest: MiddlewareManifest = JSON.parse( await promises.readFile(
await promises.readFile( path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST),
path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST), 'utf8'
'utf8'
)
) )
)
await promises.writeFile( await promises.writeFile(
path.join( path.join(
distDir, distDir,
CLIENT_STATIC_FILES_PATH, CLIENT_STATIC_FILES_PATH,
buildId, buildId,
'_middlewareManifest.js' '_middlewareManifest.js'
), ),
`self.__MIDDLEWARE_MANIFEST=${devalue( `self.__MIDDLEWARE_MANIFEST=${devalue(
middlewareManifest.sortedMiddleware middlewareManifest.sortedMiddleware
)};self.__MIDDLEWARE_MANIFEST_CB&&self.__MIDDLEWARE_MANIFEST_CB()` )};self.__MIDDLEWARE_MANIFEST_CB&&self.__MIDDLEWARE_MANIFEST_CB()`
) )
}
const images = { ...config.images } const images = { ...config.images }
const { deviceSizes, imageSizes } = images const { deviceSizes, imageSizes } = images
......
...@@ -946,7 +946,6 @@ export default async function getBaseWebpackConfig( ...@@ -946,7 +946,6 @@ export default async function getBaseWebpackConfig(
parallel: config.experimental.cpus, parallel: config.experimental.cpus,
swcMinify: config.experimental.swcMinify, swcMinify: config.experimental.swcMinify,
terserOptions, terserOptions,
middlewareEnabled: config.experimental.middleware,
}).apply(compiler) }).apply(compiler)
}, },
// Minify CSS // Minify CSS
...@@ -1197,9 +1196,6 @@ export default async function getBaseWebpackConfig( ...@@ -1197,9 +1196,6 @@ export default async function getBaseWebpackConfig(
}), }),
'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath), 'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath),
'process.env.__NEXT_HAS_REWRITES': JSON.stringify(hasRewrites), 'process.env.__NEXT_HAS_REWRITES': JSON.stringify(hasRewrites),
'process.env.__NEXT_HAS_MIDDLEWARE': JSON.stringify(
config.experimental.middleware
),
'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),
...@@ -1278,9 +1274,7 @@ export default async function getBaseWebpackConfig( ...@@ -1278,9 +1274,7 @@ export default async function getBaseWebpackConfig(
new PagesManifestPlugin({ serverless: isLikeServerless, dev }), new PagesManifestPlugin({ serverless: isLikeServerless, dev }),
// MiddlewarePlugin should be after DefinePlugin so NEXT_PUBLIC_* // MiddlewarePlugin should be after DefinePlugin so NEXT_PUBLIC_*
// replacement is done before its process.env.* handling // replacement is done before its process.env.* handling
!isServer && !isServer && new MiddlewarePlugin({ dev }),
config.experimental.middleware &&
new MiddlewarePlugin({ dev }),
isServer && new NextJsSsrImportPlugin(), isServer && new NextJsSsrImportPlugin(),
!isServer && !isServer &&
new BuildManifestPlugin({ new BuildManifestPlugin({
......
...@@ -49,20 +49,13 @@ function buildError(error, file) { ...@@ -49,20 +49,13 @@ function buildError(error, file) {
export class TerserPlugin { export class TerserPlugin {
constructor(options = {}) { constructor(options = {}) {
const { const { cacheDir, terserOptions = {}, parallel, swcMinify } = options
cacheDir,
terserOptions = {},
parallel,
swcMinify,
middlewareEnabled,
} = options
this.options = { this.options = {
swcMinify, swcMinify,
cacheDir, cacheDir,
parallel, parallel,
terserOptions, terserOptions,
middlewareEnabled,
} }
} }
...@@ -106,17 +99,15 @@ export class TerserPlugin { ...@@ -106,17 +99,15 @@ export class TerserPlugin {
} }
// remove below if we start minifying middleware chunks // remove below if we start minifying middleware chunks
if (this.options.middlewareEnabled) { if (name.startsWith('static/chunks/webpack-')) {
if (name.startsWith('static/chunks/webpack-')) { webpackAsset = name
webpackAsset = name }
}
// don't minify _middleware as it can break in some cases // don't minify _middleware as it can break in some cases
// and doesn't provide too much of a benefit as it's server-side // and doesn't provide too much of a benefit as it's server-side
if (name.match(/(middleware-chunks|_middleware\.js$)/)) { if (name.match(/(middleware-chunks|_middleware\.js$)/)) {
hasMiddleware = true hasMiddleware = true
return false return false
}
} }
const { info } = res const { info } = res
......
...@@ -85,31 +85,27 @@ export default class PageLoader { ...@@ -85,31 +85,27 @@ export default class PageLoader {
} }
getMiddlewareList(): Promise<string[]> { getMiddlewareList(): Promise<string[]> {
if (process.env.__NEXT_HAS_MIDDLEWARE) { if (process.env.NODE_ENV === 'production') {
if (process.env.NODE_ENV === 'production') { return getMiddlewareManifest()
return getMiddlewareManifest() } else {
if ((window as any).__DEV_MIDDLEWARE_MANIFEST) {
return (window as any).__DEV_MIDDLEWARE_MANIFEST
} else { } else {
if ((window as any).__DEV_MIDDLEWARE_MANIFEST) { if (!this.promisedMiddlewareManifest) {
return (window as any).__DEV_MIDDLEWARE_MANIFEST this.promisedMiddlewareManifest = fetch(
} else { `${this.assetPrefix}/_next/static/${this.buildId}/_devMiddlewareManifest.json`
if (!this.promisedMiddlewareManifest) { )
this.promisedMiddlewareManifest = fetch( .then((res) => res.json())
`${this.assetPrefix}/_next/static/${this.buildId}/_devMiddlewareManifest.json` .then((manifest) => {
) ;(window as any).__DEV_MIDDLEWARE_MANIFEST = manifest
.then((res) => res.json()) return manifest
.then((manifest) => { })
;(window as any).__DEV_MIDDLEWARE_MANIFEST = manifest .catch((err) => {
return manifest console.log(`Failed to fetch _devMiddlewareManifest`, err)
}) })
.catch((err) => {
console.log(`Failed to fetch _devMiddlewareManifest`, err)
})
}
return this.promisedMiddlewareManifest
} }
return this.promisedMiddlewareManifest
} }
} else {
return Promise.resolve([])
} }
} }
......
...@@ -232,32 +232,27 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> { ...@@ -232,32 +232,27 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> {
markAssetError(new Error('Failed to load client build manifest')) markAssetError(new Error('Failed to load client build manifest'))
) )
} }
let _getMiddlewareManifest = () => Promise.resolve([])
if (process.env.__NEXT_HAS_MIDDLEWARE) { export function getMiddlewareManifest(): Promise<any> {
_getMiddlewareManifest = async () => { if (self.__MIDDLEWARE_MANIFEST) {
if (self.__MIDDLEWARE_MANIFEST) { return Promise.resolve(self.__MIDDLEWARE_MANIFEST)
return Promise.resolve(self.__MIDDLEWARE_MANIFEST) }
}
const onMiddlewareManifest: Promise<any> = new Promise<any>((resolve) => { const onMiddlewareManifest: Promise<any> = new Promise<any>((resolve) => {
const cb = self.__MIDDLEWARE_MANIFEST_CB const cb = self.__MIDDLEWARE_MANIFEST_CB
self.__MIDDLEWARE_MANIFEST_CB = () => { self.__MIDDLEWARE_MANIFEST_CB = () => {
resolve(self.__MIDDLEWARE_MANIFEST!) resolve(self.__MIDDLEWARE_MANIFEST!)
cb && cb() cb && cb()
} }
}) })
return resolvePromiseWithTimeout( return resolvePromiseWithTimeout(
onMiddlewareManifest, onMiddlewareManifest,
MS_MAX_IDLE_DELAY, MS_MAX_IDLE_DELAY,
markAssetError(new Error('Failed to load client middleware manifest')) markAssetError(new Error('Failed to load client middleware manifest'))
) )
}
} }
export const getMiddlewareManifest = _getMiddlewareManifest
interface RouteFiles { interface RouteFiles {
scripts: string[] scripts: string[]
css: string[] css: string[]
......
...@@ -119,7 +119,6 @@ export type NextConfig = { [key: string]: any } & { ...@@ -119,7 +119,6 @@ export type NextConfig = { [key: string]: any } & {
staticPageGenerationTimeout?: number staticPageGenerationTimeout?: number
crossOrigin?: false | 'anonymous' | 'use-credentials' crossOrigin?: false | 'anonymous' | 'use-credentials'
experimental?: { experimental?: {
middleware?: boolean
swcMinify?: boolean swcMinify?: boolean
swcLoader?: boolean swcLoader?: boolean
cpus?: number cpus?: number
...@@ -204,7 +203,6 @@ export const defaultConfig: NextConfig = { ...@@ -204,7 +203,6 @@ export const defaultConfig: NextConfig = {
}, },
staticPageGenerationTimeout: 60, staticPageGenerationTimeout: 60,
experimental: { experimental: {
middleware: false,
swcLoader: false, swcLoader: false,
swcMinify: false, swcMinify: false,
cpus: Math.max( cpus: Math.max(
......
...@@ -265,12 +265,10 @@ export default class DevServer extends Server { ...@@ -265,12 +265,10 @@ export default class DevServer extends Server {
routedPages.push(pageName) routedPages.push(pageName)
} }
if (this.nextConfig.experimental.middleware) { this.middleware = getSortedRoutes(routedMiddleware).map((page) => ({
this.middleware = getSortedRoutes(routedMiddleware).map((page) => ({ match: getRouteMatcher(getMiddlewareRegex(page)),
match: getRouteMatcher(getMiddlewareRegex(page)), page,
page, }))
}))
}
try { try {
// we serve a separate manifest with all pages for the client in // we serve a separate manifest with all pages for the client in
...@@ -693,27 +691,25 @@ export default class DevServer extends Server { ...@@ -693,27 +691,25 @@ export default class DevServer extends Server {
}, },
}) })
if (this.nextConfig.experimental.middleware) { fsRoutes.unshift({
fsRoutes.unshift({ match: route(
match: route( `/_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`
`/_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}` ),
), type: 'route',
type: 'route', name: `_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`,
name: `_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`, fn: async (_req, res) => {
fn: async (_req, res) => { res.statusCode = 200
res.statusCode = 200 res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.setHeader('Content-Type', 'application/json; charset=utf-8') res.end(
res.end( JSON.stringify(
JSON.stringify( this.middleware?.map((middleware) => middleware.page) || []
this.middleware?.map((middleware) => middleware.page) || []
)
) )
return { )
finished: true, return {
} finished: true,
}, }
}) },
} })
fsRoutes.push({ fsRoutes.push({
match: route('/:path*'), match: route('/:path*'),
......
...@@ -281,7 +281,7 @@ export default class Server { ...@@ -281,7 +281,7 @@ export default class Server {
if (!dev) { if (!dev) {
this.pagesManifest = require(pagesManifestPath) this.pagesManifest = require(pagesManifestPath)
if (!this.minimalMode && this.nextConfig.experimental.middleware) { if (!this.minimalMode) {
this.middlewareManifest = require(middlewareManifestPath) this.middlewareManifest = require(middlewareManifestPath)
} }
} }
...@@ -569,9 +569,6 @@ export default class Server { ...@@ -569,9 +569,6 @@ export default class Server {
} }
protected getMiddleware() { protected getMiddleware() {
if (!this.nextConfig.experimental.middleware) {
return []
}
return Object.keys(this.middlewareManifest?.middleware || {}).map( return Object.keys(this.middlewareManifest?.middleware || {}).map(
(page) => ({ (page) => ({
match: getRouteMatcher(getMiddlewareRegex(page)), match: getRouteMatcher(getMiddlewareRegex(page)),
...@@ -597,12 +594,23 @@ export default class Server { ...@@ -597,12 +594,23 @@ export default class Server {
protected async ensureMiddleware(_pathname: string) {} protected async ensureMiddleware(_pathname: string) {}
private middlewareBetaWarning = execOnce(() => {
console.warn(
chalk.bold.yellow(`Warning: `) +
chalk.yellow(
`using beta Middleware (not covered by semver) - https://nextjs.org/docs/messages/beta-middleware`
)
)
})
protected async runMiddleware(params: { protected async runMiddleware(params: {
request: IncomingMessage request: IncomingMessage
response: ServerResponse response: ServerResponse
parsedUrl: ParsedNextUrl parsedUrl: ParsedNextUrl
parsed: UrlWithParsedQuery parsed: UrlWithParsedQuery
}): Promise<FetchEventResult | null> { }): Promise<FetchEventResult | null> {
this.middlewareBetaWarning()
const page: { name?: string; params?: { [key: string]: string } } = {} const page: { name?: string; params?: { [key: string]: string } } = {}
if (await this.hasPage(params.parsedUrl.pathname)) { if (await this.hasPage(params.parsedUrl.pathname)) {
page.name = params.parsedUrl.pathname page.name = params.parsedUrl.pathname
...@@ -1085,7 +1093,7 @@ export default class Server { ...@@ -1085,7 +1093,7 @@ export default class Server {
let catchAllMiddleware: Route | undefined let catchAllMiddleware: Route | undefined
if (!this.minimalMode && this.nextConfig.experimental.middleware) { if (!this.minimalMode) {
catchAllMiddleware = { catchAllMiddleware = {
match: route('/:path*'), match: route('/:path*'),
type: 'route', type: 'route',
......
This diff is collapsed.
module.exports = { module.exports = {
basePath: '/root', basePath: '/root',
experimental: {
middleware: true,
},
} }
...@@ -3,7 +3,4 @@ module.exports = { ...@@ -3,7 +3,4 @@ module.exports = {
locales: ['en', 'fr', 'nl'], locales: ['en', 'fr', 'nl'],
defaultLocale: 'en', defaultLocale: 'en',
}, },
experimental: {
middleware: true,
},
} }
...@@ -17,11 +17,22 @@ jest.setTimeout(1000 * 60 * 2) ...@@ -17,11 +17,22 @@ jest.setTimeout(1000 * 60 * 2)
const context = {} const context = {}
context.appDir = join(__dirname, '../') context.appDir = join(__dirname, '../')
const middlewareWarning =
'Warning: using beta Middleware (not covered by semver)'
describe('Middleware base tests', () => { describe('Middleware base tests', () => {
describe('dev mode', () => { describe('dev mode', () => {
let output = ''
beforeAll(async () => { beforeAll(async () => {
context.appPort = await findPort() context.appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort) context.app = await launchApp(context.appDir, context.appPort, {
onStdout(msg) {
output += msg
},
onStderr(msg) {
output += msg
},
})
}) })
afterAll(() => killApp(context.app)) afterAll(() => killApp(context.app))
rewriteTests() rewriteTests()
...@@ -32,12 +43,31 @@ describe('Middleware base tests', () => { ...@@ -32,12 +43,31 @@ describe('Middleware base tests', () => {
responseTests('/fr') responseTests('/fr')
interfaceTests() interfaceTests()
interfaceTests('/fr') interfaceTests('/fr')
it('should have showed warning for middleware usage', () => {
expect(output).toContain(middlewareWarning)
})
}) })
describe('production mode', () => { describe('production mode', () => {
let buildOutput
let serverOutput
beforeAll(async () => { beforeAll(async () => {
await nextBuild(context.appDir) const res = await nextBuild(context.appDir, undefined, {
stderr: true,
stdout: true,
})
buildOutput = res.stdout + res.stderr
context.appPort = await findPort() context.appPort = await findPort()
context.app = await nextStart(context.appDir, context.appPort) context.app = await nextStart(context.appDir, context.appPort, {
onStdout(msg) {
serverOutput += msg
},
onStderr(msg) {
serverOutput += msg
},
})
}) })
afterAll(() => killApp(context.app)) afterAll(() => killApp(context.app))
rewriteTests() rewriteTests()
...@@ -49,6 +79,14 @@ describe('Middleware base tests', () => { ...@@ -49,6 +79,14 @@ describe('Middleware base tests', () => {
interfaceTests() interfaceTests()
interfaceTests('/fr') interfaceTests('/fr')
it('should have middleware warning during build', () => {
expect(buildOutput).toContain(middlewareWarning)
})
it('should have middleware warning during start', () => {
expect(serverOutput).toContain(middlewareWarning)
})
it('should have correct files in manifest', async () => { it('should have correct files in manifest', async () => {
const manifest = await fs.readJSON( const manifest = await fs.readJSON(
join(context.appDir, '.next/server/middleware-manifest.json') join(context.appDir, '.next/server/middleware-manifest.json')
......
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