Skip to content

Commit

Permalink
Revert "fix the dynamic routing of middleware" (#35932)
Browse files Browse the repository at this point in the history
Reverts #32601
  • Loading branch information
nkzawa committed Apr 6, 2022
1 parent d3af135 commit 9805399
Show file tree
Hide file tree
Showing 34 changed files with 261 additions and 922 deletions.
35 changes: 9 additions & 26 deletions packages/next/build/index.ts
Expand Up @@ -450,18 +450,12 @@ export default async function build(
namedRegex?: string
routeKeys?: { [key: string]: string }
}>
dynamicRoutes: Array<
| {
page: string
regex: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}
| {
page: string
isMiddleware: true
}
>
dynamicRoutes: Array<{
page: string
regex: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}>
dataRoutes: Array<{
page: string
routeKeys?: { [key: string]: string }
Expand All @@ -480,14 +474,14 @@ export default async function build(
localeDetection?: false
}
} = nextBuildSpan.traceChild('generate-routes-manifest').traceFn(() => ({
version: 4,
version: 3,
pages404: true,
basePath: config.basePath,
redirects: redirects.map((r: any) => buildCustomRoute(r, 'redirect')),
headers: headers.map((r: any) => buildCustomRoute(r, 'header')),
dynamicRoutes: getSortedRoutes(pageKeys)
.filter((page) => isDynamicRoute(page))
.map(pageToRouteOrMiddleware),
.filter((page) => isDynamicRoute(page) && !page.match(MIDDLEWARE_ROUTE))
.map(pageToRoute),
staticRoutes: getSortedRoutes(pageKeys)
.filter(
(page) =>
Expand Down Expand Up @@ -2206,14 +2200,3 @@ function pageToRoute(page: string) {
namedRegex: routeRegex.namedRegex,
}
}

function pageToRouteOrMiddleware(page: string) {
if (page.match(MIDDLEWARE_ROUTE)) {
return {
page: page.replace(/\/_middleware$/, '') || '/',
isMiddleware: true as const,
}
}

return pageToRoute(page)
}
91 changes: 43 additions & 48 deletions packages/next/server/base-server.ts
Expand Up @@ -29,9 +29,10 @@ import {
TEMPORARY_REDIRECT_STATUS,
} from '../shared/lib/constants'
import {
getRoutingItems,
getRouteMatcher,
getRouteRegex,
getSortedRoutes,
isDynamicRoute,
RoutingItem,
} from '../shared/lib/router/utils'
import {
setLazyProp,
Expand Down Expand Up @@ -70,6 +71,12 @@ export type FindComponentsResult = {
query: NextParsedUrlQuery
}

interface RoutingItem {
page: string
match: ReturnType<typeof getRouteMatcher>
ssr?: boolean
}

export interface Options {
/**
* Object containing the configuration next.config.js
Expand Down Expand Up @@ -170,8 +177,8 @@ export default abstract class Server {
protected dynamicRoutes?: DynamicRoutes
protected customRoutes: CustomRoutes
protected middlewareManifest?: MiddlewareManifest
protected middleware?: RoutingItem[]
protected serverComponentManifest?: any
protected allRoutes?: RoutingItem[]
public readonly hostname?: string
public readonly port?: number

Expand All @@ -183,8 +190,7 @@ export default abstract class Server {
protected abstract generateImageRoutes(): Route[]
protected abstract generateStaticRoutes(): Route[]
protected abstract generateFsStaticRoutes(): Route[]
protected abstract generateCatchAllStaticMiddlewareRoute(): Route | undefined
protected abstract generateCatchAllDynamicMiddlewareRoute(): Route | undefined
protected abstract generateCatchAllMiddlewareRoute(): Route | undefined
protected abstract generateRewrites({
restrictedRedirectPaths,
}: {
Expand All @@ -195,6 +201,14 @@ export default abstract class Server {
fallback: Route[]
}
protected abstract getFilesystemPaths(): Set<string>
protected abstract getMiddleware(): {
match: (pathname: string | null | undefined) =>
| false
| {
[paramName: string]: string | string[]
}
page: string
}[]
protected abstract findPageComponents(
pathname: string,
query?: NextParsedUrlQuery,
Expand Down Expand Up @@ -640,11 +654,9 @@ export default abstract class Server {
fallback: Route[]
}
fsRoutes: Route[]
internalFsRoutes: Route[]
redirects: Route[]
catchAllRoute: Route
catchAllStaticMiddleware?: Route
catchAllDynamicMiddleware?: Route
catchAllMiddleware?: Route
pageChecker: PageChecker
useFileSystemPublicRoutes: boolean
dynamicRoutes: DynamicRoutes | undefined
Expand All @@ -654,7 +666,7 @@ export default abstract class Server {
const imageRoutes = this.generateImageRoutes()
const staticFilesRoutes = this.generateStaticRoutes()

const internalFsRoutes: Route[] = [
const fsRoutes: Route[] = [
...this.generateFsStaticRoutes(),
{
match: route('/_next/data/:path*'),
Expand Down Expand Up @@ -744,10 +756,10 @@ export default abstract class Server {
}
},
},
...publicRoutes,
...staticFilesRoutes,
]

const fsRoutes: Route[] = [...publicRoutes, ...staticFilesRoutes]

const restrictedRedirectPaths = this.nextConfig.basePath
? [`${this.nextConfig.basePath}/_next`]
: ['/_next']
Expand All @@ -766,10 +778,7 @@ export default abstract class Server {
)

const rewrites = this.generateRewrites({ restrictedRedirectPaths })
const catchAllStaticMiddleware =
this.generateCatchAllStaticMiddlewareRoute()
const catchAllDynamicMiddleware =
this.generateCatchAllDynamicMiddlewareRoute()
const catchAllMiddleware = this.generateCatchAllMiddlewareRoute()

const catchAllRoute: Route = {
match: route('/:path*'),
Expand Down Expand Up @@ -804,7 +813,7 @@ export default abstract class Server {
}
}

if (isApiRoute(pathname)) {
if (pathname === '/api' || pathname.startsWith('/api/')) {
delete query._nextBubbleNoFallback

const handled = await this.handleApiRequest(req, res, pathname, query)
Expand Down Expand Up @@ -833,19 +842,19 @@ export default abstract class Server {
const { useFileSystemPublicRoutes } = this.nextConfig

if (useFileSystemPublicRoutes) {
this.allRoutes = this.getAllRoutes()
this.dynamicRoutes = this.getDynamicRoutes()
if (!this.minimalMode) {
this.middleware = this.getMiddleware()
}
}

return {
headers,
fsRoutes,
internalFsRoutes,
rewrites,
redirects,
catchAllRoute,
catchAllStaticMiddleware,
catchAllDynamicMiddleware,
catchAllMiddleware,
useFileSystemPublicRoutes,
dynamicRoutes: this.dynamicRoutes,
basePath: this.nextConfig.basePath,
Expand Down Expand Up @@ -922,34 +931,24 @@ export default abstract class Server {
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> {
const addedPages = new Set<string>()

return this.allRoutes!.filter((item) => {
if (
item.isMiddleware ||
addedPages.has(item.page) ||
!isDynamicRoute(item.page)
return getSortedRoutes(
Object.keys(this.pagesManifest!).map(
(page) =>
normalizeLocalePath(page, this.nextConfig.i18n?.locales).pathname
)
return false
addedPages.add(item.page)
return true
})
)
.map((page) => {
if (addedPages.has(page) || !isDynamicRoute(page)) return null
addedPages.add(page)
return {
page,
match: getRouteMatcher(getRouteRegex(page)),
}
})
.filter((item): item is RoutingItem => Boolean(item))
}

protected async run(
Expand Down Expand Up @@ -1941,10 +1940,6 @@ export function prepareServerlessUrl(

export { stringifyQuery } from './server-route-utils'

export function isApiRoute(pathname: string) {
return pathname === '/api' || pathname.startsWith('/api/')
}

class NoFallbackError extends Error {}

// Internal wrapper around build errors at development
Expand Down

0 comments on commit 9805399

Please sign in to comment.