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 page: string
regex: string regex: string
namedRegex?: string namedRegex?: string
routeKeys?: { [key: string]: 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 getDynamicRoutes(): Array<RoutingItem> { protected getAllRoutes(): RoutingItem[] {
const addedPages = new Set<string>() const pages = Object.keys(this.pagesManifest!).map(
return getSortedRoutes(
Object.keys(this.pagesManifest!).map(
(page) => (page) =>
normalizeLocalePath(page, this.nextConfig.i18n?.locales).pathname normalizeLocalePath(page, this.nextConfig.i18n?.locales).pathname
) )
) const middlewareMap = this.minimalMode
.map((page) => { ? {}
if (addedPages.has(page) || !isDynamicRoute(page)) return null : this.middlewareManifest?.middleware || {}
addedPages.add(page) const middleware = Object.keys(middlewareMap).map((page) => ({
return {
page, page,
match: getRouteMatcher(getRouteRegex(page)), ssr: !MIDDLEWARE_ROUTE.test(middlewareMap[page].name),
}))
return getRoutingItems(pages, middleware)
} }
protected getDynamicRoutes(): Array<RoutingItem> {
const addedPages = new Set<string>()
return this.allRoutes!.filter((item) => {
if (
item.isMiddleware ||
addedPages.has(item.page) ||
!isDynamicRoute(item.page)
)
return false
addedPages.add(item.page)
return true
}) })
.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({
page:
`/${relative(pagesDir!, fileName).replace(/\\+/g, '/')}` `/${relative(pagesDir!, fileName).replace(/\\+/g, '/')}`
.replace(/^\/+/g, '/') .replace(/^\/+/g, '/')
.replace(regexMiddleware, '/') .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 []
......
...@@ -3,7 +3,7 @@ import type { Params, Route } from './router' ...@@ -3,7 +3,7 @@ import type { Params, Route } from './router'
import type { CacheFs } from '../shared/lib/utils' import type { CacheFs } from '../shared/lib/utils'
import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin' import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'
import type RenderResult from './render-result' import type RenderResult from './render-result'
import type { FetchEventResult } from './web/types' import type { FetchEventResult, RequestData } from './web/types'
import type { ParsedNextUrl } from '../shared/lib/router/utils/parse-next-url' import type { ParsedNextUrl } from '../shared/lib/router/utils/parse-next-url'
import type { PrerenderManifest } from '../build' import type { PrerenderManifest } from '../build'
import type { Rewrite } from '../lib/load-custom-routes' import type { Rewrite } from '../lib/load-custom-routes'
...@@ -57,6 +57,7 @@ import BaseServer, { ...@@ -57,6 +57,7 @@ import BaseServer, {
FindComponentsResult, FindComponentsResult,
prepareServerlessUrl, prepareServerlessUrl,
stringifyQuery, stringifyQuery,
isApiRoute,
} from './base-server' } from './base-server'
import { getMiddlewareInfo, getPagePath, requireFontManifest } from './require' import { getMiddlewareInfo, getPagePath, requireFontManifest } from './require'
import { normalizePagePath } from './normalize-page-path' import { normalizePagePath } from './normalize-page-path'
...@@ -68,14 +69,14 @@ import { relativizeURL } from '../shared/lib/router/utils/relativize-url' ...@@ -68,14 +69,14 @@ import { relativizeURL } from '../shared/lib/router/utils/relativize-url'
import { parseNextUrl } from '../shared/lib/router/utils/parse-next-url' import { parseNextUrl } from '../shared/lib/router/utils/parse-next-url'
import { prepareDestination } from '../shared/lib/router/utils/prepare-destination' import { prepareDestination } from '../shared/lib/router/utils/prepare-destination'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { getMiddlewareRegex, getRouteMatcher } from '../shared/lib/router/utils' import { RoutingItem } from '../shared/lib/router/utils'
import { MIDDLEWARE_ROUTE } from '../lib/constants'
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
import { getCustomRoute } from './server-route-utils' import { getCustomRoute } from './server-route-utils'
import { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring' import { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring'
import ResponseCache from '../server/response-cache' import ResponseCache from '../server/response-cache'
import { removePathTrailingSlash } from '../client/normalize-trailing-slash' import { removePathTrailingSlash } from '../client/normalize-trailing-slash'
import { clonableBodyForRequest } from './body-streams' import { clonableBodyForRequest } from './body-streams'
import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
export * from './base-server' export * from './base-server'
...@@ -1022,15 +1023,58 @@ export default class NextNodeServer extends BaseServer { ...@@ -1022,15 +1023,58 @@ export default class NextNodeServer extends BaseServer {
} }
} }
protected generateCatchAllMiddlewareRoute(): Route | undefined { protected generateCatchAllStaticMiddlewareRoute(): Route | undefined {
if (this.minimalMode) return undefined if (this.minimalMode) return undefined
return { return {
match: route('/:path*'), match: route('/:path*'),
type: 'route', type: 'route',
name: 'middleware catchall', name: 'static middleware catchall',
fn: async (req, res, _params, parsed) => { fn: async (req, res, _params, parsed) => {
if (!this.middleware?.length) { return await this.handleMiddlewareRoute({
isDynamic: false,
req,
res,
parsed,
})
},
}
}
protected generateCatchAllDynamicMiddlewareRoute(): Route | undefined {
if (this.minimalMode) return undefined
return {
match: route('/:path*'),
type: 'route',
name: 'dynamic middleware catchall',
fn: async (req, res, _params, parsed) => {
return await this.handleMiddlewareRoute({
isDynamic: true,
req,
res,
parsed,
})
},
}
}
private async handleMiddlewareRoute({
isDynamic,
parsed,
req,
res,
}: {
isDynamic: boolean
parsed: NextUrlWithParsedQuery
req: BaseNextRequest
res: BaseNextResponse
}) {
if (
!this.allRoutes?.some(
(r) => r.isMiddleware && isDynamicRoute(r.page) === isDynamic
)
) {
return { finished: false } return { finished: false }
} }
...@@ -1044,9 +1088,19 @@ export default class NextNodeServer extends BaseServer { ...@@ -1044,9 +1088,19 @@ export default class NextNodeServer extends BaseServer {
trailingSlash: this.nextConfig.trailingSlash, trailingSlash: this.nextConfig.trailingSlash,
}, },
}) })
const normalizedPathname = removePathTrailingSlash(parsedUrl.pathname) const normalizedPathname = removePathTrailingSlash(parsedUrl.pathname)
if (!this.middleware?.some((m) => m.match(normalizedPathname))) {
const middleware: RoutingItem[] = []
for (const item of this.allRoutes || []) {
if (item.match(normalizedPathname)) {
if (!item.isMiddleware) break
if (isDynamicRoute(item.page) !== isDynamic) continue
middleware.push(item)
}
}
if (!middleware.length) {
return { finished: false } return { finished: false }
} }
...@@ -1058,6 +1112,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1058,6 +1112,7 @@ export default class NextNodeServer extends BaseServer {
response: res, response: res,
parsedUrl: parsedUrl, parsedUrl: parsedUrl,
parsed: parsed, parsed: parsed,
middleware,
}) })
} catch (err) { } catch (err) {
if (isError(err) && err.code === 'ENOENT') { if (isError(err) && err.code === 'ENOENT') {
...@@ -1134,9 +1189,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1134,9 +1189,7 @@ export default class NextNodeServer extends BaseServer {
} }
if (result.response.headers.has('x-middleware-rewrite')) { if (result.response.headers.has('x-middleware-rewrite')) {
const rewritePath = result.response.headers.get( const rewritePath = result.response.headers.get('x-middleware-rewrite')!
'x-middleware-rewrite'
)!
const parsedDestination = parseUrl(rewritePath) const parsedDestination = parseUrl(rewritePath)
const newUrl = parsedDestination.pathname const newUrl = parsedDestination.pathname
...@@ -1165,8 +1218,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1165,8 +1218,7 @@ export default class NextNodeServer extends BaseServer {
this.nextConfig.i18n.locales this.nextConfig.i18n.locales
) )
if (localePathResult.detectedLocale) { if (localePathResult.detectedLocale) {
parsedDestination.query.__nextLocale = parsedDestination.query.__nextLocale = localePathResult.detectedLocale
localePathResult.detectedLocale
} }
} }
...@@ -1194,20 +1246,6 @@ export default class NextNodeServer extends BaseServer { ...@@ -1194,20 +1246,6 @@ export default class NextNodeServer extends BaseServer {
return { return {
finished: false, finished: false,
} }
},
}
}
protected getMiddleware() {
const middleware = this.middlewareManifest?.middleware || {}
return (
this.middlewareManifest?.sortedMiddleware.map((page) => ({
match: getRouteMatcher(
getMiddlewareRegex(page, MIDDLEWARE_ROUTE.test(middleware[page].name))
),
page,
})) || []
)
} }
private middlewareBetaWarning = execOnce(() => { private middlewareBetaWarning = execOnce(() => {
...@@ -1221,6 +1259,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1221,6 +1259,7 @@ export default class NextNodeServer extends BaseServer {
response: BaseNextResponse response: BaseNextResponse
parsedUrl: ParsedNextUrl parsedUrl: ParsedNextUrl
parsed: UrlWithParsedQuery parsed: UrlWithParsedQuery
middleware: RoutingItem[]
onWarning?: (warning: Error) => void onWarning?: (warning: Error) => void
}): Promise<FetchEventResult | null> { }): Promise<FetchEventResult | null> {
this.middlewareBetaWarning() this.middlewareBetaWarning()
...@@ -1236,11 +1275,15 @@ export default class NextNodeServer extends BaseServer { ...@@ -1236,11 +1275,15 @@ export default class NextNodeServer extends BaseServer {
) )
} }
const page: { name?: string; params?: { [key: string]: string } } = {} const page: RequestData['page'] = {}
if (await this.hasPage(normalizedPathname)) { if (await this.hasPage(normalizedPathname)) {
page.name = params.parsedUrl.pathname page.name = params.parsedUrl.pathname
} else if (this.dynamicRoutes) { } else if (this.dynamicRoutes) {
const isApi = isApiRoute(normalizedPathname)
for (const dynamicRoute of this.dynamicRoutes) { for (const dynamicRoute of this.dynamicRoutes) {
// The api route should not match with others
if (isApi && !isApiRoute(dynamicRoute.page)) continue
const matchParams = dynamicRoute.match(normalizedPathname) const matchParams = dynamicRoute.match(normalizedPathname)
if (matchParams) { if (matchParams) {
page.name = dynamicRoute.page page.name = dynamicRoute.page
...@@ -1258,7 +1301,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1258,7 +1301,7 @@ export default class NextNodeServer extends BaseServer {
? clonableBodyForRequest(params.request.body) ? clonableBodyForRequest(params.request.body)
: undefined : undefined
for (const middleware of this.middleware || []) { for (const middleware of params.middleware) {
if (middleware.match(normalizedPathname)) { if (middleware.match(normalizedPathname)) {
if (!(await this.hasMiddleware(middleware.page, middleware.ssr))) { if (!(await this.hasMiddleware(middleware.page, middleware.ssr))) {
console.warn(`The Edge Function for ${middleware.page} was not found`) console.warn(`The Edge Function for ${middleware.page} was not found`)
......
...@@ -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