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,7 +1720,6 @@ export default async function build( ...@@ -1718,7 +1720,6 @@ 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),
...@@ -1737,7 +1738,6 @@ export default async function build( ...@@ -1737,7 +1738,6 @@ export default async function build(
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,7 +99,6 @@ export class TerserPlugin { ...@@ -106,7 +99,6 @@ 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
} }
...@@ -117,7 +109,6 @@ export class TerserPlugin { ...@@ -117,7 +109,6 @@ export class TerserPlugin {
hasMiddleware = true hasMiddleware = true
return false return false
} }
}
const { info } = res const { info } = res
......
...@@ -85,7 +85,6 @@ export default class PageLoader { ...@@ -85,7 +85,6 @@ 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 { } else {
...@@ -108,9 +107,6 @@ export default class PageLoader { ...@@ -108,9 +107,6 @@ export default class PageLoader {
return this.promisedMiddlewareManifest return this.promisedMiddlewareManifest
} }
} }
} else {
return Promise.resolve([])
}
} }
/** /**
......
...@@ -232,10 +232,8 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> { ...@@ -232,10 +232,8 @@ 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)
} }
...@@ -253,11 +251,8 @@ if (process.env.__NEXT_HAS_MIDDLEWARE) { ...@@ -253,11 +251,8 @@ if (process.env.__NEXT_HAS_MIDDLEWARE) {
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,7 +691,6 @@ export default class DevServer extends Server { ...@@ -693,7 +691,6 @@ 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}`
...@@ -713,7 +710,6 @@ export default class DevServer extends Server { ...@@ -713,7 +710,6 @@ export default class DevServer extends Server {
} }
}, },
}) })
}
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',
......
...@@ -35,13 +35,7 @@ import { searchParamsToUrlQuery } from './utils/querystring' ...@@ -35,13 +35,7 @@ import { searchParamsToUrlQuery } from './utils/querystring'
import resolveRewrites from './utils/resolve-rewrites' import resolveRewrites from './utils/resolve-rewrites'
import { getRouteMatcher } from './utils/route-matcher' import { getRouteMatcher } from './utils/route-matcher'
import { getRouteRegex } from './utils/route-regex' import { getRouteRegex } from './utils/route-regex'
import { getMiddlewareRegex } from './utils/get-middleware-regex'
let getMiddlewareRegex: typeof import('./utils/get-middleware-regex').getMiddlewareRegex
if (process.env.__NEXT_HAS_MIDDLEWARE) {
getMiddlewareRegex =
require('./utils/get-middleware-regex').getMiddlewareRegex
}
declare global { declare global {
interface Window { interface Window {
...@@ -1100,7 +1094,6 @@ export default class Router implements BaseRouter { ...@@ -1100,7 +1094,6 @@ export default class Router implements BaseRouter {
resolvedAs = delLocale(delBasePath(resolvedAs), this.locale) resolvedAs = delLocale(delBasePath(resolvedAs), this.locale)
if (process.env.__NEXT_HAS_MIDDLEWARE) {
const effect = await this._preflightRequest({ const effect = await this._preflightRequest({
as, as,
cache: process.env.NODE_ENV === 'production', cache: process.env.NODE_ENV === 'production',
...@@ -1124,7 +1117,6 @@ export default class Router implements BaseRouter { ...@@ -1124,7 +1117,6 @@ export default class Router implements BaseRouter {
window.location.href = as window.location.href = as
return new Promise(() => {}) return new Promise(() => {})
} }
}
const route = removePathTrailingSlash(pathname) const route = removePathTrailingSlash(pathname)
...@@ -1651,7 +1643,6 @@ export default class Router implements BaseRouter { ...@@ -1651,7 +1643,6 @@ export default class Router implements BaseRouter {
return return
} }
if (process.env.__NEXT_HAS_MIDDLEWARE) {
const effects = await this._preflightRequest({ const effects = await this._preflightRequest({
as: asPath, as: asPath,
cache: true, cache: true,
...@@ -1667,7 +1658,6 @@ export default class Router implements BaseRouter { ...@@ -1667,7 +1658,6 @@ export default class Router implements BaseRouter {
resolvedAs = effects.asPath resolvedAs = effects.asPath
url = formatWithValidation(parsed) url = formatWithValidation(parsed)
} }
}
const route = removePathTrailingSlash(pathname) const route = removePathTrailingSlash(pathname)
...@@ -1751,7 +1741,6 @@ export default class Router implements BaseRouter { ...@@ -1751,7 +1741,6 @@ export default class Router implements BaseRouter {
pathname: string pathname: string
query: ParsedUrlQuery query: ParsedUrlQuery
}): Promise<PreflightEffect> { }): Promise<PreflightEffect> {
if (process.env.__NEXT_HAS_MIDDLEWARE) {
const cleanedAs = delLocale( const cleanedAs = delLocale(
hasBasePath(options.as) ? delBasePath(options.as) : options.as, hasBasePath(options.as) ? delBasePath(options.as) : options.as,
this.locale this.locale
...@@ -1849,14 +1838,11 @@ export default class Router implements BaseRouter { ...@@ -1849,14 +1838,11 @@ export default class Router implements BaseRouter {
type: 'next', type: 'next',
} }
} }
return { type: 'next' }
}
_getPreflightData(params: { _getPreflightData(params: {
preflightHref: string preflightHref: string
shouldCache?: boolean shouldCache?: boolean
}): Promise<PreflightData> { }): Promise<PreflightData> {
if (process.env.__NEXT_HAS_MIDDLEWARE) {
const { preflightHref, shouldCache = false } = params const { preflightHref, shouldCache = false } = params
const { href: cacheKey } = new URL(preflightHref, window.location.href) const { href: cacheKey } = new URL(preflightHref, window.location.href)
...@@ -1896,9 +1882,6 @@ export default class Router implements BaseRouter { ...@@ -1896,9 +1882,6 @@ export default class Router implements BaseRouter {
delete this.sde[cacheKey] delete this.sde[cacheKey]
throw err throw err
}) })
} else {
return {} as any
}
} }
_getStaticData(dataHref: string): Promise<object> { _getStaticData(dataHref: string): Promise<object> {
......
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