Unverified Commit 53d1b00c authored by Naoyuki Kanezawa's avatar Naoyuki Kanezawa Committed by GitHub

fix the dynamic routing of middleware (#32601)

* fix the dynamic routing of middleware

* add middleware to dynamicRoutes of routes-manifest

* remove unused import

* fix middleware routing with static paths

* update manifest version test

* prevent to match with api route using regex

* use iterator instead of generator

* do not use Iterator

* fix type

* fix type

* remove unused import

* apply the fix for support colons
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 5d1f33f5
...@@ -447,12 +447,18 @@ export default async function build( ...@@ -447,12 +447,18 @@ export default async function build(
namedRegex?: string namedRegex?: string
routeKeys?: { [key: string]: string } routeKeys?: { [key: string]: string }
}> }>
dynamicRoutes: Array<{ dynamicRoutes: Array<
page: string | {
regex: string page: string
namedRegex?: string regex: string
routeKeys?: { [key: string]: string } namedRegex?: string
}> routeKeys?: { [key: string]: string }
}
| {
page: string
isMiddleware: true
}
>
dataRoutes: Array<{ dataRoutes: Array<{
page: string page: string
routeKeys?: { [key: string]: string } routeKeys?: { [key: string]: string }
...@@ -471,14 +477,14 @@ export default async function build( ...@@ -471,14 +477,14 @@ export default async function build(
localeDetection?: false localeDetection?: false
} }
} = nextBuildSpan.traceChild('generate-routes-manifest').traceFn(() => ({ } = nextBuildSpan.traceChild('generate-routes-manifest').traceFn(() => ({
version: 3, version: 4,
pages404: true, pages404: true,
basePath: config.basePath, basePath: config.basePath,
redirects: redirects.map((r: any) => buildCustomRoute(r, 'redirect')), redirects: redirects.map((r: any) => buildCustomRoute(r, 'redirect')),
headers: headers.map((r: any) => buildCustomRoute(r, 'header')), headers: headers.map((r: any) => buildCustomRoute(r, 'header')),
dynamicRoutes: getSortedRoutes(pageKeys) dynamicRoutes: getSortedRoutes(pageKeys)
.filter((page) => isDynamicRoute(page) && !page.match(MIDDLEWARE_ROUTE)) .filter((page) => isDynamicRoute(page))
.map(pageToRoute), .map(pageToRouteOrMiddleware),
staticRoutes: getSortedRoutes(pageKeys) staticRoutes: getSortedRoutes(pageKeys)
.filter( .filter(
(page) => (page) =>
...@@ -2190,3 +2196,14 @@ function pageToRoute(page: string) { ...@@ -2190,3 +2196,14 @@ function pageToRoute(page: string) {
namedRegex: routeRegex.namedRegex, namedRegex: routeRegex.namedRegex,
} }
} }
function pageToRouteOrMiddleware(page: string) {
if (page.match(MIDDLEWARE_ROUTE)) {
return {
page: page.replace(/\/_middleware$/, '') || '/',
isMiddleware: true as const,
}
}
return pageToRoute(page)
}
...@@ -29,10 +29,9 @@ import { ...@@ -29,10 +29,9 @@ import {
TEMPORARY_REDIRECT_STATUS, TEMPORARY_REDIRECT_STATUS,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { import {
getRouteMatcher, getRoutingItems,
getRouteRegex,
getSortedRoutes,
isDynamicRoute, isDynamicRoute,
RoutingItem,
} from '../shared/lib/router/utils' } from '../shared/lib/router/utils'
import { import {
setLazyProp, setLazyProp,
...@@ -71,12 +70,6 @@ export type FindComponentsResult = { ...@@ -71,12 +70,6 @@ export type FindComponentsResult = {
query: NextParsedUrlQuery query: NextParsedUrlQuery
} }
interface RoutingItem {
page: string
match: ReturnType<typeof getRouteMatcher>
ssr?: boolean
}
export interface Options { export interface Options {
/** /**
* Object containing the configuration next.config.js * Object containing the configuration next.config.js
...@@ -177,8 +170,8 @@ export default abstract class Server { ...@@ -177,8 +170,8 @@ export default abstract class Server {
protected dynamicRoutes?: DynamicRoutes protected dynamicRoutes?: DynamicRoutes
protected customRoutes: CustomRoutes protected customRoutes: CustomRoutes
protected middlewareManifest?: MiddlewareManifest protected middlewareManifest?: MiddlewareManifest
protected middleware?: RoutingItem[]
protected serverComponentManifest?: any protected serverComponentManifest?: any
protected allRoutes?: RoutingItem[]
public readonly hostname?: string public readonly hostname?: string
public readonly port?: number public readonly port?: number
...@@ -190,7 +183,8 @@ export default abstract class Server { ...@@ -190,7 +183,8 @@ export default abstract class Server {
protected abstract generateImageRoutes(): Route[] protected abstract generateImageRoutes(): Route[]
protected abstract generateStaticRoutes(): Route[] protected abstract generateStaticRoutes(): Route[]
protected abstract generateFsStaticRoutes(): Route[] protected abstract generateFsStaticRoutes(): Route[]
protected abstract generateCatchAllMiddlewareRoute(): Route | undefined protected abstract generateCatchAllStaticMiddlewareRoute(): Route | undefined
protected abstract generateCatchAllDynamicMiddlewareRoute(): Route | undefined
protected abstract generateRewrites({ protected abstract generateRewrites({
restrictedRedirectPaths, restrictedRedirectPaths,
}: { }: {
...@@ -201,14 +195,6 @@ export default abstract class Server { ...@@ -201,14 +195,6 @@ export default abstract class Server {
fallback: Route[] fallback: Route[]
} }
protected abstract getFilesystemPaths(): Set<string> protected abstract getFilesystemPaths(): Set<string>
protected abstract getMiddleware(): {
match: (pathname: string | null | undefined) =>
| false
| {
[paramName: string]: string | string[]
}
page: string
}[]
protected abstract findPageComponents( protected abstract findPageComponents(
pathname: string, pathname: string,
query?: NextParsedUrlQuery, query?: NextParsedUrlQuery,
...@@ -654,9 +640,11 @@ export default abstract class Server { ...@@ -654,9 +640,11 @@ export default abstract class Server {
fallback: Route[] fallback: Route[]
} }
fsRoutes: Route[] fsRoutes: Route[]
internalFsRoutes: Route[]
redirects: Route[] redirects: Route[]
catchAllRoute: Route catchAllRoute: Route
catchAllMiddleware?: Route catchAllStaticMiddleware?: Route
catchAllDynamicMiddleware?: Route
pageChecker: PageChecker pageChecker: PageChecker
useFileSystemPublicRoutes: boolean useFileSystemPublicRoutes: boolean
dynamicRoutes: DynamicRoutes | undefined dynamicRoutes: DynamicRoutes | undefined
...@@ -666,7 +654,7 @@ export default abstract class Server { ...@@ -666,7 +654,7 @@ export default abstract class Server {
const imageRoutes = this.generateImageRoutes() const imageRoutes = this.generateImageRoutes()
const staticFilesRoutes = this.generateStaticRoutes() const staticFilesRoutes = this.generateStaticRoutes()
const fsRoutes: Route[] = [ const internalFsRoutes: Route[] = [
...this.generateFsStaticRoutes(), ...this.generateFsStaticRoutes(),
{ {
match: route('/_next/data/:path*'), match: route('/_next/data/:path*'),
...@@ -756,10 +744,10 @@ export default abstract class Server { ...@@ -756,10 +744,10 @@ export default abstract class Server {
} }
}, },
}, },
...publicRoutes,
...staticFilesRoutes,
] ]
const fsRoutes: Route[] = [...publicRoutes, ...staticFilesRoutes]
const restrictedRedirectPaths = this.nextConfig.basePath const restrictedRedirectPaths = this.nextConfig.basePath
? [`${this.nextConfig.basePath}/_next`] ? [`${this.nextConfig.basePath}/_next`]
: ['/_next'] : ['/_next']
...@@ -778,7 +766,10 @@ export default abstract class Server { ...@@ -778,7 +766,10 @@ export default abstract class Server {
) )
const rewrites = this.generateRewrites({ restrictedRedirectPaths }) const rewrites = this.generateRewrites({ restrictedRedirectPaths })
const catchAllMiddleware = this.generateCatchAllMiddlewareRoute() const catchAllStaticMiddleware =
this.generateCatchAllStaticMiddlewareRoute()
const catchAllDynamicMiddleware =
this.generateCatchAllDynamicMiddlewareRoute()
const catchAllRoute: Route = { const catchAllRoute: Route = {
match: route('/:path*'), match: route('/:path*'),
...@@ -813,7 +804,7 @@ export default abstract class Server { ...@@ -813,7 +804,7 @@ export default abstract class Server {
} }
} }
if (pathname === '/api' || pathname.startsWith('/api/')) { if (isApiRoute(pathname)) {
delete query._nextBubbleNoFallback delete query._nextBubbleNoFallback
const handled = await this.handleApiRequest(req, res, pathname, query) const handled = await this.handleApiRequest(req, res, pathname, query)
...@@ -842,19 +833,19 @@ export default abstract class Server { ...@@ -842,19 +833,19 @@ export default abstract class Server {
const { useFileSystemPublicRoutes } = this.nextConfig const { useFileSystemPublicRoutes } = this.nextConfig
if (useFileSystemPublicRoutes) { if (useFileSystemPublicRoutes) {
this.allRoutes = this.getAllRoutes()
this.dynamicRoutes = this.getDynamicRoutes() this.dynamicRoutes = this.getDynamicRoutes()
if (!this.minimalMode) {
this.middleware = this.getMiddleware()
}
} }
return { return {
headers, headers,
fsRoutes, fsRoutes,
internalFsRoutes,
rewrites, rewrites,
redirects, redirects,
catchAllRoute, catchAllRoute,
catchAllMiddleware, catchAllStaticMiddleware,
catchAllDynamicMiddleware,
useFileSystemPublicRoutes, useFileSystemPublicRoutes,
dynamicRoutes: this.dynamicRoutes, dynamicRoutes: this.dynamicRoutes,
basePath: this.nextConfig.basePath, basePath: this.nextConfig.basePath,
...@@ -931,24 +922,34 @@ export default abstract class Server { ...@@ -931,24 +922,34 @@ export default abstract class Server {
return this.runApi(req, res, query, params, page, builtPagePath) return this.runApi(req, res, query, params, page, builtPagePath)
} }
protected getAllRoutes(): RoutingItem[] {
const pages = Object.keys(this.pagesManifest!).map(
(page) =>
normalizeLocalePath(page, this.nextConfig.i18n?.locales).pathname
)
const middlewareMap = this.minimalMode
? {}
: this.middlewareManifest?.middleware || {}
const middleware = Object.keys(middlewareMap).map((page) => ({
page,
ssr: !MIDDLEWARE_ROUTE.test(middlewareMap[page].name),
}))
return getRoutingItems(pages, middleware)
}
protected getDynamicRoutes(): Array<RoutingItem> { protected getDynamicRoutes(): Array<RoutingItem> {
const addedPages = new Set<string>() const addedPages = new Set<string>()
return getSortedRoutes( return this.allRoutes!.filter((item) => {
Object.keys(this.pagesManifest!).map( if (
(page) => item.isMiddleware ||
normalizeLocalePath(page, this.nextConfig.i18n?.locales).pathname addedPages.has(item.page) ||
!isDynamicRoute(item.page)
) )
) return false
.map((page) => { addedPages.add(item.page)
if (addedPages.has(page) || !isDynamicRoute(page)) return null return true
addedPages.add(page) })
return {
page,
match: getRouteMatcher(getRouteRegex(page)),
}
})
.filter((item): item is RoutingItem => Boolean(item))
} }
protected async run( protected async run(
...@@ -1926,6 +1927,10 @@ export function prepareServerlessUrl( ...@@ -1926,6 +1927,10 @@ export function prepareServerlessUrl(
export { stringifyQuery } from './server-route-utils' export { stringifyQuery } from './server-route-utils'
export function isApiRoute(pathname: string) {
return pathname === '/api' || pathname.startsWith('/api/')
}
class NoFallbackError extends Error {} class NoFallbackError extends Error {}
// Internal wrapper around build errors at development // Internal wrapper around build errors at development
......
...@@ -34,10 +34,9 @@ import { ...@@ -34,10 +34,9 @@ import {
DEV_MIDDLEWARE_MANIFEST, DEV_MIDDLEWARE_MANIFEST,
} from '../../shared/lib/constants' } from '../../shared/lib/constants'
import { import {
getRouteMatcher, getRoutingItems,
getRouteRegex,
getSortedRoutes,
isDynamicRoute, isDynamicRoute,
RoutingItem,
} from '../../shared/lib/router/utils' } from '../../shared/lib/router/utils'
import Server, { WrappedBuildError } from '../next-server' import Server, { WrappedBuildError } from '../next-server'
import { normalizePagePath } from '../normalize-page-path' import { normalizePagePath } from '../normalize-page-path'
...@@ -59,7 +58,6 @@ import { ...@@ -59,7 +58,6 @@ import {
} from 'next/dist/compiled/@next/react-dev-overlay/middleware' } from 'next/dist/compiled/@next/react-dev-overlay/middleware'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import isError, { getProperError } from '../../lib/is-error' import isError, { getProperError } from '../../lib/is-error'
import { getMiddlewareRegex } from '../../shared/lib/router/utils/get-middleware-regex'
import { isCustomErrorPage, isReservedPage } from '../../build/utils' import { isCustomErrorPage, isReservedPage } from '../../build/utils'
import { NodeNextResponse, NodeNextRequest } from '../base-http/node' import { NodeNextResponse, NodeNextRequest } from '../base-http/node'
import { getPageRuntime, invalidatePageRuntimeCache } from '../../build/entries' import { getPageRuntime, invalidatePageRuntimeCache } from '../../build/entries'
...@@ -93,6 +91,7 @@ export default class DevServer extends Server { ...@@ -93,6 +91,7 @@ export default class DevServer extends Server {
private isCustomServer: boolean private isCustomServer: boolean
protected sortedRoutes?: string[] protected sortedRoutes?: string[]
private addedUpgradeListener = false private addedUpgradeListener = false
private middleware?: RoutingItem[]
protected staticPathsWorker?: { [key: string]: any } & { protected staticPathsWorker?: { [key: string]: any } & {
loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths
...@@ -261,7 +260,6 @@ export default class DevServer extends Server { ...@@ -261,7 +260,6 @@ export default class DevServer extends Server {
const routedMiddleware = [] const routedMiddleware = []
const routedPages = [] const routedPages = []
const knownFiles = wp.getTimeInfoEntries() const knownFiles = wp.getTimeInfoEntries()
const ssrMiddleware = new Set<string>()
for (const [fileName, { accuracy, safeTime }] of knownFiles) { for (const [fileName, { accuracy, safeTime }] of knownFiles) {
if (accuracy === undefined || !regexPageExtension.test(fileName)) { if (accuracy === undefined || !regexPageExtension.test(fileName)) {
...@@ -269,11 +267,13 @@ export default class DevServer extends Server { ...@@ -269,11 +267,13 @@ export default class DevServer extends Server {
} }
if (regexMiddleware.test(fileName)) { if (regexMiddleware.test(fileName)) {
routedMiddleware.push( routedMiddleware.push({
`/${relative(pagesDir!, fileName).replace(/\\+/g, '/')}` page:
.replace(/^\/+/g, '/') `/${relative(pagesDir!, fileName).replace(/\\+/g, '/')}`
.replace(regexMiddleware, '/') .replace(/^\/+/g, '/')
) .replace(regexMiddleware, '') || '/',
ssr: false,
})
continue continue
} }
...@@ -293,26 +293,22 @@ export default class DevServer extends Server { ...@@ -293,26 +293,22 @@ export default class DevServer extends Server {
isEdgeRuntime && isEdgeRuntime &&
!(isReservedPage(pageName) || isCustomErrorPage(pageName)) !(isReservedPage(pageName) || isCustomErrorPage(pageName))
) { ) {
routedMiddleware.push(pageName) routedMiddleware.push({ page: pageName, ssr: true })
ssrMiddleware.add(pageName)
} }
routedPages.push(pageName) routedPages.push(pageName)
} }
this.middleware = getSortedRoutes(routedMiddleware).map((page) => ({ this.allRoutes = getRoutingItems(routedPages, routedMiddleware)
match: getRouteMatcher( this.middleware = this.allRoutes.filter((r) => r.isMiddleware)
getMiddlewareRegex(page, !ssrMiddleware.has(page))
),
page,
ssr: ssrMiddleware.has(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
// dev mode so that we can match a page after a rewrite on the client // dev mode so that we can match a page after a rewrite on the client
// before it has been built and is populated in the _buildManifest // before it has been built and is populated in the _buildManifest
const sortedRoutes = getSortedRoutes(routedPages) const sortedRoutes = this.allRoutes
.filter((r) => !r.isMiddleware)
.map((r) => r.page)
if ( if (
!this.sortedRoutes?.every((val, idx) => val === sortedRoutes[idx]) !this.sortedRoutes?.every((val, idx) => val === sortedRoutes[idx])
...@@ -322,12 +318,9 @@ export default class DevServer extends Server { ...@@ -322,12 +318,9 @@ export default class DevServer extends Server {
} }
this.sortedRoutes = sortedRoutes this.sortedRoutes = sortedRoutes
this.dynamicRoutes = this.sortedRoutes this.dynamicRoutes = this.allRoutes.filter(
.filter(isDynamicRoute) (r) => !r.isMiddleware && isDynamicRoute(r.page)
.map((page) => ({ )
page,
match: getRouteMatcher(getRouteRegex(page)),
}))
this.router.setDynamicRoutes(this.dynamicRoutes) this.router.setDynamicRoutes(this.dynamicRoutes)
...@@ -535,6 +528,7 @@ export default class DevServer extends Server { ...@@ -535,6 +528,7 @@ export default class DevServer extends Server {
response: BaseNextResponse response: BaseNextResponse
parsedUrl: ParsedNextUrl parsedUrl: ParsedNextUrl
parsed: UrlWithParsedQuery parsed: UrlWithParsedQuery
middleware: RoutingItem[]
}): Promise<FetchEventResult | null> { }): Promise<FetchEventResult | null> {
try { try {
const result = await super.runMiddleware({ const result = await super.runMiddleware({
...@@ -749,11 +743,12 @@ export default class DevServer extends Server { ...@@ -749,11 +743,12 @@ export default class DevServer extends Server {
} }
generateRoutes() { generateRoutes() {
const { fsRoutes, ...otherRoutes } = super.generateRoutes() const { fsRoutes, internalFsRoutes, ...otherRoutes } =
super.generateRoutes()
// In development we expose all compiled files for react-error-overlay's line show feature // In development we expose all compiled files for react-error-overlay's line show feature
// We use unshift so that we're sure the routes is defined before Next's default routes // We use unshift so that we're sure the routes is defined before Next's default routes
fsRoutes.unshift({ internalFsRoutes.unshift({
match: route('/_next/development/:path*'), match: route('/_next/development/:path*'),
type: 'route', type: 'route',
name: '_next/development catchall', name: '_next/development catchall',
...@@ -766,7 +761,7 @@ export default class DevServer extends Server { ...@@ -766,7 +761,7 @@ export default class DevServer extends Server {
}, },
}) })
fsRoutes.unshift({ internalFsRoutes.unshift({
match: route( match: route(
`/_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_CLIENT_PAGES_MANIFEST}` `/_next/${CLIENT_STATIC_FILES_PATH}/${this.buildId}/${DEV_CLIENT_PAGES_MANIFEST}`
), ),
...@@ -788,7 +783,7 @@ export default class DevServer extends Server { ...@@ -788,7 +783,7 @@ export default class DevServer extends Server {
}, },
}) })
fsRoutes.unshift({ internalFsRoutes.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}`
), ),
...@@ -837,7 +832,7 @@ export default class DevServer extends Server { ...@@ -837,7 +832,7 @@ export default class DevServer extends Server {
}, },
}) })
return { fsRoutes, ...otherRoutes } return { fsRoutes, internalFsRoutes, ...otherRoutes }
} }
// In development public files are not added to the router but handled as a fallback instead // In development public files are not added to the router but handled as a fallback instead
...@@ -845,6 +840,10 @@ export default class DevServer extends Server { ...@@ -845,6 +840,10 @@ export default class DevServer extends Server {
return [] return []
} }
protected getAllRoutes(): RoutingItem[] {
return []
}
// In development dynamic routes cannot be known ahead of time // In development dynamic routes cannot be known ahead of time
protected getDynamicRoutes(): never[] { protected getDynamicRoutes(): never[] {
return [] return []
......
This diff is collapsed.
...@@ -66,6 +66,7 @@ export default class Router { ...@@ -66,6 +66,7 @@ export default class Router {
basePath: string basePath: string
headers: Route[] headers: Route[]
fsRoutes: Route[] fsRoutes: Route[]
internalFsRoutes: Route[]
redirects: Route[] redirects: Route[]
rewrites: { rewrites: {
beforeFiles: Route[] beforeFiles: Route[]
...@@ -73,7 +74,8 @@ export default class Router { ...@@ -73,7 +74,8 @@ export default class Router {
fallback: Route[] fallback: Route[]
} }
catchAllRoute: Route catchAllRoute: Route
catchAllMiddleware?: Route catchAllStaticMiddleware?: Route
catchAllDynamicMiddleware?: Route
pageChecker: PageChecker pageChecker: PageChecker
dynamicRoutes: DynamicRoutes dynamicRoutes: DynamicRoutes
useFileSystemPublicRoutes: boolean useFileSystemPublicRoutes: boolean
...@@ -84,6 +86,7 @@ export default class Router { ...@@ -84,6 +86,7 @@ export default class Router {
basePath = '', basePath = '',
headers = [], headers = [],
fsRoutes = [], fsRoutes = [],
internalFsRoutes = [],
rewrites = { rewrites = {
beforeFiles: [], beforeFiles: [],
afterFiles: [], afterFiles: [],
...@@ -91,7 +94,8 @@ export default class Router { ...@@ -91,7 +94,8 @@ export default class Router {
}, },
redirects = [], redirects = [],
catchAllRoute, catchAllRoute,
catchAllMiddleware, catchAllStaticMiddleware,
catchAllDynamicMiddleware,
dynamicRoutes = [], dynamicRoutes = [],
pageChecker, pageChecker,
useFileSystemPublicRoutes, useFileSystemPublicRoutes,
...@@ -100,6 +104,7 @@ export default class Router { ...@@ -100,6 +104,7 @@ export default class Router {
basePath: string basePath: string
headers: Route[] headers: Route[]
fsRoutes: Route[] fsRoutes: Route[]
internalFsRoutes: Route[]
rewrites: { rewrites: {
beforeFiles: Route[] beforeFiles: Route[]
afterFiles: Route[] afterFiles: Route[]
...@@ -107,7 +112,8 @@ export default class Router { ...@@ -107,7 +112,8 @@ export default class Router {
} }
redirects: Route[] redirects: Route[]
catchAllRoute: Route catchAllRoute: Route
catchAllMiddleware?: Route catchAllStaticMiddleware?: Route
catchAllDynamicMiddleware?: Route
dynamicRoutes: DynamicRoutes | undefined dynamicRoutes: DynamicRoutes | undefined
pageChecker: PageChecker pageChecker: PageChecker
useFileSystemPublicRoutes: boolean useFileSystemPublicRoutes: boolean
...@@ -116,11 +122,13 @@ export default class Router { ...@@ -116,11 +122,13 @@ export default class Router {
this.basePath = basePath this.basePath = basePath
this.headers = headers this.headers = headers
this.fsRoutes = fsRoutes this.fsRoutes = fsRoutes
this.internalFsRoutes = internalFsRoutes
this.rewrites = rewrites this.rewrites = rewrites
this.redirects = redirects this.redirects = redirects
this.pageChecker = pageChecker this.pageChecker = pageChecker
this.catchAllRoute = catchAllRoute this.catchAllRoute = catchAllRoute
this.catchAllMiddleware = catchAllMiddleware this.catchAllStaticMiddleware = catchAllStaticMiddleware
this.catchAllDynamicMiddleware = catchAllDynamicMiddleware
this.dynamicRoutes = dynamicRoutes this.dynamicRoutes = dynamicRoutes
this.useFileSystemPublicRoutes = useFileSystemPublicRoutes this.useFileSystemPublicRoutes = useFileSystemPublicRoutes
this.locales = locales this.locales = locales
...@@ -166,7 +174,7 @@ export default class Router { ...@@ -166,7 +174,7 @@ export default class Router {
const originalFsPathname = checkParsedUrl.pathname const originalFsPathname = checkParsedUrl.pathname
const fsPathname = replaceBasePath(originalFsPathname!, this.basePath) const fsPathname = replaceBasePath(originalFsPathname!, this.basePath)
for (const fsRoute of this.fsRoutes) { for (const fsRoute of [...this.internalFsRoutes, ...this.fsRoutes]) {
const fsParams = fsRoute.match(fsPathname) const fsParams = fsRoute.match(fsPathname)
if (fsParams) { if (fsParams) {
...@@ -225,10 +233,14 @@ export default class Router { ...@@ -225,10 +233,14 @@ export default class Router {
...this.headers, ...this.headers,
...this.redirects, ...this.redirects,
...this.rewrites.beforeFiles, ...this.rewrites.beforeFiles,
...(this.useFileSystemPublicRoutes && this.catchAllMiddleware ...this.internalFsRoutes,
? [this.catchAllMiddleware] ...(this.useFileSystemPublicRoutes && this.catchAllStaticMiddleware
? [this.catchAllStaticMiddleware]
: []), : []),
...this.fsRoutes, ...this.fsRoutes,
...(this.useFileSystemPublicRoutes && this.catchAllDynamicMiddleware
? [this.catchAllDynamicMiddleware]
: []),
// We only check the catch-all route if public page routes hasn't been // We only check the catch-all route if public page routes hasn't been
// disabled // disabled
...(this.useFileSystemPublicRoutes ...(this.useFileSystemPublicRoutes
...@@ -299,9 +311,15 @@ export default class Router { ...@@ -299,9 +311,15 @@ export default class Router {
const requireBasePath = testRoute.requireBasePath !== false const requireBasePath = testRoute.requireBasePath !== false
const isCustomRoute = customRouteTypes.has(testRoute.type) const isCustomRoute = customRouteTypes.has(testRoute.type)
const isPublicFolderCatchall = testRoute.name === 'public folder catchall' const isPublicFolderCatchall = testRoute.name === 'public folder catchall'
const isMiddlewareCatchall = testRoute.name === 'middleware catchall' const isStaticMiddlewareCatchall =
testRoute.name === 'static middleware catchall'
const isDynamicMiddlewareCatchall =
testRoute.name === 'dynamic middleware catchall'
const keepBasePath = const keepBasePath =
isCustomRoute || isPublicFolderCatchall || isMiddlewareCatchall isCustomRoute ||
isPublicFolderCatchall ||
isStaticMiddlewareCatchall ||
isDynamicMiddlewareCatchall
const keepLocale = isCustomRoute const keepLocale = isCustomRoute
const currentPathnameNoBasePath = replaceBasePath( const currentPathnameNoBasePath = replaceBasePath(
......
...@@ -81,7 +81,10 @@ export default class NextWebServer extends BaseServer { ...@@ -81,7 +81,10 @@ export default class NextWebServer extends BaseServer {
protected getMiddleware() { protected getMiddleware() {
return [] return []
} }
protected generateCatchAllMiddlewareRoute() { protected generateCatchAllStaticMiddlewareRoute() {
return undefined
}
protected generateCatchAllDynamicMiddlewareRoute() {
return undefined return undefined
} }
protected getFontManifest() { protected getFontManifest() {
......
...@@ -36,8 +36,8 @@ import { searchParamsToUrlQuery } from './utils/querystring' ...@@ -36,8 +36,8 @@ 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'
import { formatWithValidation } from './utils/format-url' import { formatWithValidation } from './utils/format-url'
import { getRoutingItems } from './utils/routing-items'
declare global { declare global {
interface Window { interface Window {
...@@ -1871,10 +1871,18 @@ export default class Router implements BaseRouter { ...@@ -1871,10 +1871,18 @@ export default class Router implements BaseRouter {
options.locale options.locale
) )
const fns = await this.pageLoader.getMiddlewareList() const middlewareList = await this.pageLoader.getMiddlewareList()
const requiresPreflight = fns.some(([middleware, isSSR]) => { const middleware = middlewareList.map(([page, ssr]) => ({ page, ssr }))
return getRouteMatcher(getMiddlewareRegex(middleware, !isSSR))(cleanedAs) const routingItems = getRoutingItems(options.pages, middleware)
}) let requiresPreflight = false
for (const item of routingItems) {
if (item.match(cleanedAs)) {
if (item.isMiddleware) {
requiresPreflight = true
}
break
}
}
if (!requiresPreflight) { if (!requiresPreflight) {
return { type: 'next' } return { type: 'next' }
......
import { getParametrizedRoute, RouteRegex } from './route-regex' import { getParametrizedRoute, RouteRegex } from './route-regex'
// Identify ^/[param]/ in route string
const FIRST_SEGMENT_DYNAMIC = /^\/\[[^/]+?\](?=\/|$)/
const NOT_API_ROUTE = '(?!/api(?:/|$))'
export function getMiddlewareRegex( export function getMiddlewareRegex(
normalizedRoute: string, normalizedRoute: string,
catchAll: boolean = true catchAll: boolean = true
): RouteRegex { ): RouteRegex {
const result = getParametrizedRoute(normalizedRoute) const result = getParametrizedRoute(normalizedRoute)
const notApiRegex = FIRST_SEGMENT_DYNAMIC.test(normalizedRoute)
? NOT_API_ROUTE
: ''
let catchAllRegex = catchAll ? '(?!_next).*' : '' let catchAllRegex = catchAll ? '(?!_next($|/)).*' : ''
let catchAllGroupedRegex = catchAll ? '(?:(/.*)?)' : '' let catchAllGroupedRegex = catchAll ? '(?:(/.*)?)' : ''
if ('routeKeys' in result) { if ('routeKeys' in result) {
...@@ -21,8 +29,10 @@ export function getMiddlewareRegex( ...@@ -21,8 +29,10 @@ export function getMiddlewareRegex(
return { return {
groups: result.groups, groups: result.groups,
namedRegex: `^${result.namedParameterizedRoute}${catchAllGroupedRegex}$`, namedRegex: `^${notApiRegex}${result.namedParameterizedRoute}${catchAllGroupedRegex}$`,
re: new RegExp(`^${result.parameterizedRoute}${catchAllGroupedRegex}$`), re: new RegExp(
`^${notApiRegex}${result.parameterizedRoute}${catchAllGroupedRegex}$`
),
routeKeys: result.routeKeys, routeKeys: result.routeKeys,
} }
} }
...@@ -36,6 +46,8 @@ export function getMiddlewareRegex( ...@@ -36,6 +46,8 @@ export function getMiddlewareRegex(
return { return {
groups: {}, groups: {},
re: new RegExp(`^${result.parameterizedRoute}${catchAllGroupedRegex}$`), re: new RegExp(
`^${notApiRegex}${result.parameterizedRoute}${catchAllGroupedRegex}$`
),
} }
} }
export { getMiddlewareRegex } from './get-middleware-regex' export { getMiddlewareRegex } from './get-middleware-regex'
export { getRouteMatcher } from './route-matcher' export { getRouteMatcher } from './route-matcher'
export { getRouteRegex } from './route-regex' export { getRouteRegex } from './route-regex'
export { getRoutingItems, RoutingItem } from './routing-items'
export { getSortedRoutes } from './sorted-routes' export { getSortedRoutes } from './sorted-routes'
export { isDynamicRoute } from './is-dynamic' export { isDynamicRoute } from './is-dynamic'
import { getMiddlewareRegex } from './get-middleware-regex'
import { getRouteMatcher } from './route-matcher'
import { getRouteRegex } from './route-regex'
import { getSortedRoutes } from './sorted-routes'
const MIDDLEWARE_SUFFIX = '/_middleware'
export interface RoutingItem {
page: string
match: ReturnType<typeof getRouteMatcher>
ssr?: boolean
isMiddleware?: boolean
}
export function getRoutingItems(
pages: string[],
middleware: { page: string; ssr: boolean }[]
): RoutingItem[] {
// append the suffix so that `getSortedRoutes()` can handle middleware properly
const middlewarePages = middleware.map((m) => `${m.page}${MIDDLEWARE_SUFFIX}`)
const middlewareMap = new Map(middleware.map((m) => [m.page, m]))
const sortedRoutes = getSortedRoutes([...pages, ...middlewarePages])
return sortedRoutes.map((page) => {
if (page.endsWith(MIDDLEWARE_SUFFIX)) {
const p = page.slice(0, -MIDDLEWARE_SUFFIX.length) || '/'
const { ssr } = middlewareMap.get(p)!
return {
match: getRouteMatcher(getMiddlewareRegex(p, !ssr)),
page: p,
ssr,
isMiddleware: true,
}
} else {
return {
match: getRouteMatcher(getRouteRegex(page)),
page,
}
}
})
}
...@@ -4,6 +4,7 @@ class UrlNode { ...@@ -4,6 +4,7 @@ class UrlNode {
slugName: string | null = null slugName: string | null = null
restSlugName: string | null = null restSlugName: string | null = null
optionalRestSlugName: string | null = null optionalRestSlugName: string | null = null
isMiddleware: boolean = false
insert(urlPath: string): void { insert(urlPath: string): void {
this._insert(urlPath.split('/').filter(Boolean), [], false) this._insert(urlPath.split('/').filter(Boolean), [], false)
...@@ -24,6 +25,9 @@ class UrlNode { ...@@ -24,6 +25,9 @@ class UrlNode {
if (this.optionalRestSlugName !== null) { if (this.optionalRestSlugName !== null) {
childrenPaths.splice(childrenPaths.indexOf('[[...]]'), 1) childrenPaths.splice(childrenPaths.indexOf('[[...]]'), 1)
} }
if (this.isMiddleware) {
childrenPaths.splice(childrenPaths.indexOf('_middleware'), 1)
}
const routes = childrenPaths const routes = childrenPaths
.map((c) => this.children.get(c)!._smoosh(`${prefix}${c}/`)) .map((c) => this.children.get(c)!._smoosh(`${prefix}${c}/`))
...@@ -46,6 +50,12 @@ class UrlNode { ...@@ -46,6 +50,12 @@ class UrlNode {
routes.unshift(r) routes.unshift(r)
} }
if (this.isMiddleware) {
routes.unshift(
...this.children.get('_middleware')!._smoosh(`${prefix}_middleware/`)
)
}
if (this.restSlugName !== null) { if (this.restSlugName !== null) {
routes.push( routes.push(
...this.children ...this.children
...@@ -182,6 +192,8 @@ class UrlNode { ...@@ -182,6 +192,8 @@ class UrlNode {
// nextSegment is overwritten to [] so that it can later be sorted specifically // nextSegment is overwritten to [] so that it can later be sorted specifically
nextSegment = '[]' nextSegment = '[]'
} }
} else if (nextSegment === '_middleware' && urlPaths.length === 1) {
this.isMiddleware = true
} }
// If this UrlNode doesn't have the nextSegment yet we create a new child UrlNode // If this UrlNode doesn't have the nextSegment yet we create a new child UrlNode
......
...@@ -1201,7 +1201,7 @@ const runTests = (isDev = false) => { ...@@ -1201,7 +1201,7 @@ const runTests = (isDev = false) => {
} }
expect(manifest).toEqual({ expect(manifest).toEqual({
version: 3, version: 4,
pages404: true, pages404: true,
basePath: '', basePath: '',
dataRoutes: [ dataRoutes: [
......
import { NextResponse } from 'next/server'
export function middleware() {
return NextResponse.next()
}
...@@ -1100,6 +1100,8 @@ function runTests({ dev, serverless }) { ...@@ -1100,6 +1100,8 @@ function runTests({ dev, serverless }) {
) )
for (const route of manifest.dynamicRoutes) { for (const route of manifest.dynamicRoutes) {
if (route.isMiddleware) continue
route.regex = normalizeRegEx(route.regex) route.regex = normalizeRegEx(route.regex)
// ensure regexes are valid // ensure regexes are valid
...@@ -1116,7 +1118,7 @@ function runTests({ dev, serverless }) { ...@@ -1116,7 +1118,7 @@ function runTests({ dev, serverless }) {
} }
expect(manifest).toEqual({ expect(manifest).toEqual({
version: 3, version: 4,
pages404: true, pages404: true,
basePath: '', basePath: '',
headers: [], headers: [],
...@@ -1264,6 +1266,10 @@ function runTests({ dev, serverless }) { ...@@ -1264,6 +1266,10 @@ function runTests({ dev, serverless }) {
slug: 'slug', slug: 'slug',
}, },
}, },
{
isMiddleware: true,
page: '/middleware/[slug]',
},
{ {
namedRegex: `^/on\\-mount/(?<post>[^/]+?)(?:/)?$`, namedRegex: `^/on\\-mount/(?<post>[^/]+?)(?:/)?$`,
page: '/on-mount/[post]', page: '/on-mount/[post]',
......
module.exports = {
i18n: {
locales: ['en', 'fr', 'nl'],
defaultLocale: 'en',
},
}
import { NextResponse } from 'next/server'
export function middleware() {
const response = NextResponse.next()
response.headers.set('x-slug-id-path', 'true')
return response
}
export default function Index() {
return <p className="title">Dynamic route</p>
}
import { NextResponse } from 'next/server'
export function middleware(req) {
const response = NextResponse.next()
response.headers.set('x-slug-path', 'true')
return response
}
export default function Index() {
return <p className="title">Dynamic route</p>
}
export default function Index() {
return <p className="title">Nested Static route</p>
}
import { NextResponse } from 'next/server'
export async function middleware(request) {
const response = NextResponse.next()
response.headers.set('req-url-basepath', request.nextUrl.basePath)
response.headers.set('req-url-pathname', request.nextUrl.pathname)
response.headers.set(
'req-url-query',
JSON.stringify(Object.fromEntries(request.nextUrl.searchParams.entries()))
)
response.headers.set('req-url-locale', request.nextUrl.locale)
if (request.page.name) {
response.headers.set('req-url-page', request.page.name)
}
if (request.page.params) {
response.headers.set('req-url-params', JSON.stringify(request.page.params))
}
return response
}
import { NextResponse } from 'next/server'
export function middleware() {
const response = NextResponse.next()
response.headers.set('x-api-path', 'true')
return response
}
export default function handler(req, res) {
res.status(200).json({ route: '/api' })
}
export default function CatchAll() {
return <p className="title">Catch All route</p>
}
import { NextResponse } from 'next/server'
export function middleware() {
const response = NextResponse.next()
response.headers.set('x-catch-all-path', 'true')
return response
}
import { NextResponse } from 'next/server'
export function middleware() {
const response = NextResponse.next()
response.headers.set('x-dir-path', 'true')
return response
}
export default function Dir() {
return <p className="title">Dir route</p>
}
export default function Home() {
return <p className="title">Home Page</p>
}
export default function OptionalCatchAll() {
return <p className="title">Optional Catch All route</p>
}
import { NextResponse } from 'next/server'
export function middleware() {
const response = NextResponse.next()
response.headers.set('x-optional-catch-all-path', 'true')
return response
}
export default function Index() {
return <p className="title">Static route</p>
}
User-agent: Googlebot
Disallow: /nogooglebot/
User-agent: *
Allow: /
Sitemap: http://www.example.com/sitemap.xml
This diff is collapsed.
...@@ -66,6 +66,88 @@ describe('getSortedRoutes', () => { ...@@ -66,6 +66,88 @@ describe('getSortedRoutes', () => {
`) `)
}) })
it('correctly sorts with middleware', () => {
expect(
getSortedRoutes([
'/posts',
'/[root-slug]',
'/[root-slug]/_middleware',
'/',
'/_middleware',
'/posts/[id]',
'/blog/[id]/comments/[cid]',
'/blog/abc/[id]',
'/blog/_middleware',
'/[...rest]',
'/blog/abc/post',
'/blog/abc',
'/blog/abc/_middleware',
'/blog/[id]/_middleware',
'/p1/[[...incl]]',
'/p1/_middleware',
'/p/[...rest]',
'/p/_middleware',
'/p2/[...rest]',
'/p2/[id]',
'/p2/[id]/abc',
'/p2/_middleware',
'/p2/[id]/_middleware',
'/p3/[[...rest]]',
'/p3/[id]',
'/p3/[id]/abc',
'/p3/_middleware',
'/p3/[id]/_middleware',
'/p4/_middleware/abc',
'/p4',
'/p4/not_middleware',
'/blog/[id]',
'/foo/[d]/bar/baz/[f]',
'/apples/_middleware',
'/apples/[ab]/[cd]/ef',
'/apples/[ab]/_middleware',
])
).toMatchInlineSnapshot(`
Array [
"/_middleware",
"/",
"/apples/_middleware",
"/apples/[ab]/_middleware",
"/apples/[ab]/[cd]/ef",
"/blog/_middleware",
"/blog/abc/_middleware",
"/blog/abc",
"/blog/abc/post",
"/blog/abc/[id]",
"/blog/[id]/_middleware",
"/blog/[id]",
"/blog/[id]/comments/[cid]",
"/foo/[d]/bar/baz/[f]",
"/p/_middleware",
"/p/[...rest]",
"/p1/_middleware",
"/p1/[[...incl]]",
"/p2/_middleware",
"/p2/[id]/_middleware",
"/p2/[id]",
"/p2/[id]/abc",
"/p2/[...rest]",
"/p3/_middleware",
"/p3/[id]/_middleware",
"/p3/[id]",
"/p3/[id]/abc",
"/p3/[[...rest]]",
"/p4",
"/p4/_middleware/abc",
"/p4/not_middleware",
"/posts",
"/posts/[id]",
"/[root-slug]/_middleware",
"/[root-slug]",
"/[...rest]",
]
`)
})
it('catches mismatched param names', () => { it('catches mismatched param names', () => {
expect(() => expect(() =>
getSortedRoutes([ getSortedRoutes([
......
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