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(
const isLikeServerless = isTargetLikeServerless(target)
if (page.match(MIDDLEWARE_ROUTE)) {
if (page.match(MIDDLEWARE_ROUTE) && config.experimental.middleware) {
const loaderOpts: MiddlewareLoaderOptions = {
absolutePagePath: pages[page],
page,
......
......@@ -284,6 +284,14 @@ export default async function build(
)
)
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 hasCustomErrorPage: boolean =
mappedPages['/_error'].startsWith('private-next-pages')
......@@ -1710,24 +1718,26 @@ export default async function build(
)
}
const middlewareManifest: MiddlewareManifest = JSON.parse(
await promises.readFile(
path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST),
'utf8'
if (config.experimental.middleware) {
const middlewareManifest: MiddlewareManifest = JSON.parse(
await promises.readFile(
path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST),
'utf8'
)
)
)
await promises.writeFile(
path.join(
distDir,
CLIENT_STATIC_FILES_PATH,
buildId,
'_middlewareManifest.js'
),
`self.__MIDDLEWARE_MANIFEST=${devalue(
middlewareManifest.sortedMiddleware
)};self.__MIDDLEWARE_MANIFEST_CB&&self.__MIDDLEWARE_MANIFEST_CB()`
)
await promises.writeFile(
path.join(
distDir,
CLIENT_STATIC_FILES_PATH,
buildId,
'_middlewareManifest.js'
),
`self.__MIDDLEWARE_MANIFEST=${devalue(
middlewareManifest.sortedMiddleware
)};self.__MIDDLEWARE_MANIFEST_CB&&self.__MIDDLEWARE_MANIFEST_CB()`
)
}
const images = { ...config.images }
const { deviceSizes, imageSizes } = images
......
......@@ -946,6 +946,7 @@ export default async function getBaseWebpackConfig(
parallel: config.experimental.cpus,
swcMinify: config.experimental.swcMinify,
terserOptions,
middlewareEnabled: config.experimental.middleware,
}).apply(compiler)
},
// Minify CSS
......@@ -1196,6 +1197,9 @@ export default async function getBaseWebpackConfig(
}),
'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath),
'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_DOMAINS': JSON.stringify(config.i18n?.domains),
'process.env.__NEXT_ANALYTICS_ID': JSON.stringify(config.analyticsId),
......@@ -1274,7 +1278,9 @@ export default async function getBaseWebpackConfig(
new PagesManifestPlugin({ serverless: isLikeServerless, dev }),
// MiddlewarePlugin should be after DefinePlugin so NEXT_PUBLIC_*
// replacement is done before its process.env.* handling
!isServer && new MiddlewarePlugin({ dev }),
!isServer &&
config.experimental.middleware &&
new MiddlewarePlugin({ dev }),
isServer && new NextJsSsrImportPlugin(),
!isServer &&
new BuildManifestPlugin({
......
......@@ -49,13 +49,20 @@ function buildError(error, file) {
export class TerserPlugin {
constructor(options = {}) {
const { cacheDir, terserOptions = {}, parallel, swcMinify } = options
const {
cacheDir,
terserOptions = {},
parallel,
swcMinify,
middlewareEnabled,
} = options
this.options = {
swcMinify,
cacheDir,
parallel,
terserOptions,
middlewareEnabled,
}
}
......@@ -99,15 +106,17 @@ export class TerserPlugin {
}
// remove below if we start minifying middleware chunks
if (name.startsWith('static/chunks/webpack-')) {
webpackAsset = name
}
if (this.options.middlewareEnabled) {
if (name.startsWith('static/chunks/webpack-')) {
webpackAsset = name
}
// 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
if (name.match(/(middleware-chunks|_middleware\.js$)/)) {
hasMiddleware = true
return false
// 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
if (name.match(/(middleware-chunks|_middleware\.js$)/)) {
hasMiddleware = true
return false
}
}
const { info } = res
......
......@@ -85,27 +85,31 @@ export default class PageLoader {
}
getMiddlewareList(): Promise<string[]> {
if (process.env.NODE_ENV === 'production') {
return getMiddlewareManifest()
} else {
if ((window as any).__DEV_MIDDLEWARE_MANIFEST) {
return (window as any).__DEV_MIDDLEWARE_MANIFEST
if (process.env.__NEXT_HAS_MIDDLEWARE) {
if (process.env.NODE_ENV === 'production') {
return getMiddlewareManifest()
} else {
if (!this.promisedMiddlewareManifest) {
this.promisedMiddlewareManifest = fetch(
`${this.assetPrefix}/_next/static/${this.buildId}/_devMiddlewareManifest.json`
)
.then((res) => res.json())
.then((manifest) => {
;(window as any).__DEV_MIDDLEWARE_MANIFEST = manifest
return manifest
})
.catch((err) => {
console.log(`Failed to fetch _devMiddlewareManifest`, err)
})
if ((window as any).__DEV_MIDDLEWARE_MANIFEST) {
return (window as any).__DEV_MIDDLEWARE_MANIFEST
} else {
if (!this.promisedMiddlewareManifest) {
this.promisedMiddlewareManifest = fetch(
`${this.assetPrefix}/_next/static/${this.buildId}/_devMiddlewareManifest.json`
)
.then((res) => res.json())
.then((manifest) => {
;(window as any).__DEV_MIDDLEWARE_MANIFEST = manifest
return manifest
})
.catch((err) => {
console.log(`Failed to fetch _devMiddlewareManifest`, err)
})
}
return this.promisedMiddlewareManifest
}
return this.promisedMiddlewareManifest
}
} else {
return Promise.resolve([])
}
}
......
......@@ -232,27 +232,32 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> {
markAssetError(new Error('Failed to load client build manifest'))
)
}
let _getMiddlewareManifest = () => Promise.resolve([])
export function getMiddlewareManifest(): Promise<any> {
if (self.__MIDDLEWARE_MANIFEST) {
return Promise.resolve(self.__MIDDLEWARE_MANIFEST)
}
const onMiddlewareManifest: Promise<any> = new Promise<any>((resolve) => {
const cb = self.__MIDDLEWARE_MANIFEST_CB
self.__MIDDLEWARE_MANIFEST_CB = () => {
resolve(self.__MIDDLEWARE_MANIFEST!)
cb && cb()
if (process.env.__NEXT_HAS_MIDDLEWARE) {
_getMiddlewareManifest = async () => {
if (self.__MIDDLEWARE_MANIFEST) {
return Promise.resolve(self.__MIDDLEWARE_MANIFEST)
}
})
return resolvePromiseWithTimeout(
onMiddlewareManifest,
MS_MAX_IDLE_DELAY,
markAssetError(new Error('Failed to load client middleware manifest'))
)
const onMiddlewareManifest: Promise<any> = new Promise<any>((resolve) => {
const cb = self.__MIDDLEWARE_MANIFEST_CB
self.__MIDDLEWARE_MANIFEST_CB = () => {
resolve(self.__MIDDLEWARE_MANIFEST!)
cb && cb()
}
})
return resolvePromiseWithTimeout(
onMiddlewareManifest,
MS_MAX_IDLE_DELAY,
markAssetError(new Error('Failed to load client middleware manifest'))
)
}
}
export const getMiddlewareManifest = _getMiddlewareManifest
interface RouteFiles {
scripts: string[]
css: string[]
......
......@@ -119,6 +119,7 @@ export type NextConfig = { [key: string]: any } & {
staticPageGenerationTimeout?: number
crossOrigin?: false | 'anonymous' | 'use-credentials'
experimental?: {
middleware?: boolean
swcMinify?: boolean
swcLoader?: boolean
cpus?: number
......@@ -203,6 +204,7 @@ export const defaultConfig: NextConfig = {
},
staticPageGenerationTimeout: 60,
experimental: {
middleware: false,
swcLoader: false,
swcMinify: false,
cpus: Math.max(
......
......@@ -265,10 +265,12 @@ export default class DevServer extends Server {
routedPages.push(pageName)
}
this.middleware = getSortedRoutes(routedMiddleware).map((page) => ({
match: getRouteMatcher(getMiddlewareRegex(page)),
page,
}))
if (this.nextConfig.experimental.middleware) {
this.middleware = getSortedRoutes(routedMiddleware).map((page) => ({
match: getRouteMatcher(getMiddlewareRegex(page)),
page,
}))
}
try {
// we serve a separate manifest with all pages for the client in
......@@ -691,25 +693,27 @@ export default class DevServer extends Server {
},
})
fsRoutes.unshift({
match: route(
`/_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`
),
type: 'route',
name: `_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`,
fn: async (_req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(
JSON.stringify(
this.middleware?.map((middleware) => middleware.page) || []
if (this.nextConfig.experimental.middleware) {
fsRoutes.unshift({
match: route(
`/_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`
),
type: 'route',
name: `_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_MIDDLEWARE_MANIFEST}`,
fn: async (_req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(
JSON.stringify(
this.middleware?.map((middleware) => middleware.page) || []
)
)
)
return {
finished: true,
}
},
})
return {
finished: true,
}
},
})
}
fsRoutes.push({
match: route('/:path*'),
......
......@@ -281,7 +281,7 @@ export default class Server {
if (!dev) {
this.pagesManifest = require(pagesManifestPath)
if (!this.minimalMode) {
if (!this.minimalMode && this.nextConfig.experimental.middleware) {
this.middlewareManifest = require(middlewareManifestPath)
}
}
......@@ -569,6 +569,9 @@ export default class Server {
}
protected getMiddleware() {
if (!this.nextConfig.experimental.middleware) {
return []
}
return Object.keys(this.middlewareManifest?.middleware || {}).map(
(page) => ({
match: getRouteMatcher(getMiddlewareRegex(page)),
......@@ -1082,7 +1085,7 @@ export default class Server {
let catchAllMiddleware: Route | undefined
if (!this.minimalMode) {
if (!this.minimalMode && this.nextConfig.experimental.middleware) {
catchAllMiddleware = {
match: route('/:path*'),
type: 'route',
......
......@@ -35,7 +35,13 @@ import { searchParamsToUrlQuery } from './utils/querystring'
import resolveRewrites from './utils/resolve-rewrites'
import { getRouteMatcher } from './utils/route-matcher'
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 {
interface Window {
......@@ -1094,28 +1100,30 @@ export default class Router implements BaseRouter {
resolvedAs = delLocale(delBasePath(resolvedAs), this.locale)
const effect = await this._preflightRequest({
as,
cache: process.env.NODE_ENV === 'production',
pages,
pathname,
query,
})
if (process.env.__NEXT_HAS_MIDDLEWARE) {
const effect = await this._preflightRequest({
as,
cache: process.env.NODE_ENV === 'production',
pages,
pathname,
query,
})
if (effect.type === 'rewrite') {
query = { ...query, ...effect.parsedAs.query }
resolvedAs = effect.asPath
pathname = effect.resolvedHref
parsed.pathname = effect.resolvedHref
url = formatWithValidation(parsed)
} else if (effect.type === 'redirect' && effect.newAs) {
return this.change(method, effect.newUrl, effect.newAs, options)
} else if (effect.type === 'redirect' && effect.destination) {
window.location.href = effect.destination
return new Promise(() => {})
} else if (effect.type === 'refresh') {
window.location.href = as
return new Promise(() => {})
if (effect.type === 'rewrite') {
query = { ...query, ...effect.parsedAs.query }
resolvedAs = effect.asPath
pathname = effect.resolvedHref
parsed.pathname = effect.resolvedHref
url = formatWithValidation(parsed)
} else if (effect.type === 'redirect' && effect.newAs) {
return this.change(method, effect.newUrl, effect.newAs, options)
} else if (effect.type === 'redirect' && effect.destination) {
window.location.href = effect.destination
return new Promise(() => {})
} else if (effect.type === 'refresh') {
window.location.href = as
return new Promise(() => {})
}
}
const route = removePathTrailingSlash(pathname)
......@@ -1643,20 +1651,22 @@ export default class Router implements BaseRouter {
return
}
const effects = await this._preflightRequest({
as: asPath,
cache: true,
pages,
pathname,
query,
})
if (process.env.__NEXT_HAS_MIDDLEWARE) {
const effects = await this._preflightRequest({
as: asPath,
cache: true,
pages,
pathname,
query,
})
if (effects.type === 'rewrite') {
parsed.pathname = effects.resolvedHref
pathname = effects.resolvedHref
query = { ...query, ...effects.parsedAs.query }
resolvedAs = effects.asPath
url = formatWithValidation(parsed)
if (effects.type === 'rewrite') {
parsed.pathname = effects.resolvedHref
pathname = effects.resolvedHref
query = { ...query, ...effects.parsedAs.query }
resolvedAs = effects.asPath
url = formatWithValidation(parsed)
}
}
const route = removePathTrailingSlash(pathname)
......@@ -1741,147 +1751,154 @@ export default class Router implements BaseRouter {
pathname: string
query: ParsedUrlQuery
}): Promise<PreflightEffect> {
const cleanedAs = delLocale(
hasBasePath(options.as) ? delBasePath(options.as) : options.as,
this.locale
)
const fns: string[] = await this.pageLoader.getMiddlewareList()
const requiresPreflight = fns.some((middleware) => {
return getRouteMatcher(getMiddlewareRegex(middleware))(cleanedAs)
})
if (process.env.__NEXT_HAS_MIDDLEWARE) {
const cleanedAs = delLocale(
hasBasePath(options.as) ? delBasePath(options.as) : options.as,
this.locale
)
if (!requiresPreflight) {
return { type: 'next' }
}
const fns: string[] = await this.pageLoader.getMiddlewareList()
const requiresPreflight = fns.some((middleware) => {
return getRouteMatcher(getMiddlewareRegex(middleware))(cleanedAs)
})
const preflight = await this._getPreflightData({
preflightHref: options.as,
shouldCache: options.cache,
})
if (!requiresPreflight) {
return { type: 'next' }
}
if (preflight.rewrite?.startsWith('/')) {
const parsed = parseRelativeUrl(
normalizeLocalePath(
hasBasePath(preflight.rewrite)
? delBasePath(preflight.rewrite)
: preflight.rewrite,
this.locales
).pathname
)
const preflight = await this._getPreflightData({
preflightHref: options.as,
shouldCache: options.cache,
})
const fsPathname = removePathTrailingSlash(parsed.pathname)
if (preflight.rewrite?.startsWith('/')) {
const parsed = parseRelativeUrl(
normalizeLocalePath(
hasBasePath(preflight.rewrite)
? delBasePath(preflight.rewrite)
: preflight.rewrite,
this.locales
).pathname
)
let matchedPage
let resolvedHref
const fsPathname = removePathTrailingSlash(parsed.pathname)
if (options.pages.includes(fsPathname)) {
matchedPage = true
resolvedHref = fsPathname
} else {
resolvedHref = resolveDynamicRoute(fsPathname, options.pages)
let matchedPage
let resolvedHref
if (
resolvedHref !== parsed.pathname &&
options.pages.includes(resolvedHref)
) {
if (options.pages.includes(fsPathname)) {
matchedPage = true
resolvedHref = fsPathname
} else {
resolvedHref = resolveDynamicRoute(fsPathname, options.pages)
if (
resolvedHref !== parsed.pathname &&
options.pages.includes(resolvedHref)
) {
matchedPage = true
}
}
}
return {
type: 'rewrite',
asPath: parsed.pathname,
parsedAs: parsed,
matchedPage,
resolvedHref,
return {
type: 'rewrite',
asPath: parsed.pathname,
parsedAs: parsed,
matchedPage,
resolvedHref,
}
}
}
if (preflight.redirect) {
if (preflight.redirect.startsWith('/')) {
const cleanRedirect = removePathTrailingSlash(
normalizeLocalePath(
hasBasePath(preflight.redirect)
? delBasePath(preflight.redirect)
: preflight.redirect,
this.locales
).pathname
)
if (preflight.redirect) {
if (preflight.redirect.startsWith('/')) {
const cleanRedirect = removePathTrailingSlash(
normalizeLocalePath(
hasBasePath(preflight.redirect)
? delBasePath(preflight.redirect)
: preflight.redirect,
this.locales
).pathname
)
const { url: newUrl, as: newAs } = prepareUrlAs(
this,
cleanRedirect,
cleanRedirect
)
const { url: newUrl, as: newAs } = prepareUrlAs(
this,
cleanRedirect,
cleanRedirect
)
return {
type: 'redirect',
newUrl,
newAs,
}
}
return {
type: 'redirect',
newUrl,
newAs,
destination: preflight.redirect,
}
}
return {
type: 'redirect',
destination: preflight.redirect,
if (preflight.refresh) {
return {
type: 'refresh',
}
}
}
if (preflight.refresh) {
return {
type: 'refresh',
type: 'next',
}
}
return {
type: 'next',
}
return { type: 'next' }
}
_getPreflightData(params: {
preflightHref: string
shouldCache?: boolean
}): Promise<PreflightData> {
const { preflightHref, shouldCache = false } = params
const { href: cacheKey } = new URL(preflightHref, window.location.href)
if (
process.env.NODE_ENV === 'production' &&
!this.isPreview &&
shouldCache &&
this.sde[cacheKey]
) {
return Promise.resolve(this.sde[cacheKey])
}
if (process.env.__NEXT_HAS_MIDDLEWARE) {
const { preflightHref, shouldCache = false } = params
const { href: cacheKey } = new URL(preflightHref, window.location.href)
return fetch(preflightHref, {
method: 'HEAD',
credentials: 'same-origin',
headers: { 'x-middleware-preflight': '1' },
})
.then((res) => {
if (!res.ok) {
throw new Error(`Failed to preflight request`)
}
if (
process.env.NODE_ENV === 'production' &&
!this.isPreview &&
shouldCache &&
this.sde[cacheKey]
) {
return Promise.resolve(this.sde[cacheKey])
}
return {
redirect: res.headers.get('Location'),
refresh: res.headers.has('x-middleware-refresh'),
rewrite: res.headers.get('x-middleware-rewrite'),
}
return fetch(preflightHref, {
method: 'HEAD',
credentials: 'same-origin',
headers: { 'x-middleware-preflight': '1' },
})
.then((data) => {
if (shouldCache) {
this.sde[cacheKey] = data
}
.then((res) => {
if (!res.ok) {
throw new Error(`Failed to preflight request`)
}
return data
})
.catch((err) => {
delete this.sde[cacheKey]
throw err
})
return {
redirect: res.headers.get('Location'),
refresh: res.headers.has('x-middleware-refresh'),
rewrite: res.headers.get('x-middleware-rewrite'),
}
})
.then((data) => {
if (shouldCache) {
this.sde[cacheKey] = data
}
return data
})
.catch((err) => {
delete this.sde[cacheKey]
throw err
})
} else {
return {} as any
}
}
_getStaticData(dataHref: string): Promise<object> {
......
module.exports = {
basePath: '/root',
experimental: {
middleware: true,
},
}
......@@ -3,4 +3,7 @@ module.exports = {
locales: ['en', 'fr', 'nl'],
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