Unverified Commit 7e81d13a authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add experimental config for middleware (#30154)

* Add experimental config for middleware

* Apply suggestions from code review
Co-authored-by: 's avatarSteven <steven@ceriously.com>
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent 25908cf9
...@@ -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)) { if (page.match(MIDDLEWARE_ROUTE) && config.experimental.middleware) {
const loaderOpts: MiddlewareLoaderOptions = { const loaderOpts: MiddlewareLoaderOptions = {
absolutePagePath: pages[page], absolutePagePath: pages[page],
page, page,
......
...@@ -284,6 +284,14 @@ export default async function build( ...@@ -284,6 +284,14 @@ export default async function build(
) )
) )
const pageKeys = Object.keys(mappedPages) const pageKeys = Object.keys(mappedPages)
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')
...@@ -1710,6 +1718,7 @@ export default async function build( ...@@ -1710,6 +1718,7 @@ 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),
...@@ -1728,6 +1737,7 @@ export default async function build( ...@@ -1728,6 +1737,7 @@ 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,6 +946,7 @@ export default async function getBaseWebpackConfig( ...@@ -946,6 +946,7 @@ 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
...@@ -1196,6 +1197,9 @@ export default async function getBaseWebpackConfig( ...@@ -1196,6 +1197,9 @@ 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),
...@@ -1274,7 +1278,9 @@ export default async function getBaseWebpackConfig( ...@@ -1274,7 +1278,9 @@ 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 && new MiddlewarePlugin({ dev }), !isServer &&
config.experimental.middleware &&
new MiddlewarePlugin({ dev }),
isServer && new NextJsSsrImportPlugin(), isServer && new NextJsSsrImportPlugin(),
!isServer && !isServer &&
new BuildManifestPlugin({ new BuildManifestPlugin({
......
...@@ -49,13 +49,20 @@ function buildError(error, file) { ...@@ -49,13 +49,20 @@ function buildError(error, file) {
export class TerserPlugin { export class TerserPlugin {
constructor(options = {}) { constructor(options = {}) {
const { cacheDir, terserOptions = {}, parallel, swcMinify } = options const {
cacheDir,
terserOptions = {},
parallel,
swcMinify,
middlewareEnabled,
} = options
this.options = { this.options = {
swcMinify, swcMinify,
cacheDir, cacheDir,
parallel, parallel,
terserOptions, terserOptions,
middlewareEnabled,
} }
} }
...@@ -99,6 +106,7 @@ export class TerserPlugin { ...@@ -99,6 +106,7 @@ 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
} }
...@@ -109,6 +117,7 @@ export class TerserPlugin { ...@@ -109,6 +117,7 @@ export class TerserPlugin {
hasMiddleware = true hasMiddleware = true
return false return false
} }
}
const { info } = res const { info } = res
......
...@@ -85,6 +85,7 @@ export default class PageLoader { ...@@ -85,6 +85,7 @@ 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 {
...@@ -107,6 +108,9 @@ export default class PageLoader { ...@@ -107,6 +108,9 @@ export default class PageLoader {
return this.promisedMiddlewareManifest return this.promisedMiddlewareManifest
} }
} }
} else {
return Promise.resolve([])
}
} }
/** /**
......
...@@ -232,8 +232,10 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> { ...@@ -232,8 +232,10 @@ 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([])
export function getMiddlewareManifest(): Promise<any> { if (process.env.__NEXT_HAS_MIDDLEWARE) {
_getMiddlewareManifest = async () => {
if (self.__MIDDLEWARE_MANIFEST) { if (self.__MIDDLEWARE_MANIFEST) {
return Promise.resolve(self.__MIDDLEWARE_MANIFEST) return Promise.resolve(self.__MIDDLEWARE_MANIFEST)
} }
...@@ -251,8 +253,11 @@ export function getMiddlewareManifest(): Promise<any> { ...@@ -251,8 +253,11 @@ export function getMiddlewareManifest(): Promise<any> {
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,6 +119,7 @@ export type NextConfig = { [key: string]: any } & { ...@@ -119,6 +119,7 @@ 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
...@@ -203,6 +204,7 @@ export const defaultConfig: NextConfig = { ...@@ -203,6 +204,7 @@ 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,10 +265,12 @@ export default class DevServer extends Server { ...@@ -265,10 +265,12 @@ 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
...@@ -691,6 +693,7 @@ export default class DevServer extends Server { ...@@ -691,6 +693,7 @@ 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}`
...@@ -710,6 +713,7 @@ export default class DevServer extends Server { ...@@ -710,6 +713,7 @@ 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) { if (!this.minimalMode && this.nextConfig.experimental.middleware) {
this.middlewareManifest = require(middlewareManifestPath) this.middlewareManifest = require(middlewareManifestPath)
} }
} }
...@@ -569,6 +569,9 @@ export default class Server { ...@@ -569,6 +569,9 @@ 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)),
...@@ -1082,7 +1085,7 @@ export default class Server { ...@@ -1082,7 +1085,7 @@ export default class Server {
let catchAllMiddleware: Route | undefined let catchAllMiddleware: Route | undefined
if (!this.minimalMode) { if (!this.minimalMode && this.nextConfig.experimental.middleware) {
catchAllMiddleware = { catchAllMiddleware = {
match: route('/:path*'), match: route('/:path*'),
type: 'route', type: 'route',
......
...@@ -35,7 +35,13 @@ import { searchParamsToUrlQuery } from './utils/querystring' ...@@ -35,7 +35,13 @@ 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 {
...@@ -1094,6 +1100,7 @@ export default class Router implements BaseRouter { ...@@ -1094,6 +1100,7 @@ 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',
...@@ -1117,6 +1124,7 @@ export default class Router implements BaseRouter { ...@@ -1117,6 +1124,7 @@ 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)
...@@ -1643,6 +1651,7 @@ export default class Router implements BaseRouter { ...@@ -1643,6 +1651,7 @@ 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,
...@@ -1658,6 +1667,7 @@ export default class Router implements BaseRouter { ...@@ -1658,6 +1667,7 @@ 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)
...@@ -1741,6 +1751,7 @@ export default class Router implements BaseRouter { ...@@ -1741,6 +1751,7 @@ 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
...@@ -1838,11 +1849,14 @@ export default class Router implements BaseRouter { ...@@ -1838,11 +1849,14 @@ 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)
...@@ -1882,6 +1896,9 @@ export default class Router implements BaseRouter { ...@@ -1882,6 +1896,9 @@ 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,4 +3,7 @@ module.exports = { ...@@ -3,4 +3,7 @@ module.exports = {
locales: ['en', 'fr', 'nl'], locales: ['en', 'fr', 'nl'],
defaultLocale: 'en', defaultLocale: 'en',
}, },
experimental: {
middleware: true,
},
} }
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