Unverified Commit 53e4627c authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update app router filter handling (#47761)

This ensures we check if a path is `appRouter` during prefetching so
that we can trigger hard navigations quicker when routing from pages ->
app. An additional config is also exposed to allow configuring the
potential false positive rate for the client filter.

x-ref: [slack
thread](https://vercel.slack.com/archives/C017QMYC5FB/p1680225393243459)
parent 0413fea8
...@@ -892,7 +892,8 @@ export default async function build( ...@@ -892,7 +892,8 @@ export default async function build(
appPageKeys, appPageKeys,
config.experimental.clientRouterFilterRedirects config.experimental.clientRouterFilterRedirects
? nonInternalRedirects ? nonInternalRedirects
: [] : [],
config.experimental.clientRouterFilterAllowedRate
) )
NextBuildContext.clientRouterFilters = clientRouterFilters NextBuildContext.clientRouterFilters = clientRouterFilters
......
...@@ -9,7 +9,8 @@ const POTENTIAL_ERROR_RATE = 0.01 ...@@ -9,7 +9,8 @@ const POTENTIAL_ERROR_RATE = 0.01
export function createClientRouterFilter( export function createClientRouterFilter(
paths: string[], paths: string[],
redirects: Redirect[] redirects: Redirect[],
allowedErrorRate: number = POTENTIAL_ERROR_RATE
): { ): {
staticFilter: ReturnType<BloomFilter['export']> staticFilter: ReturnType<BloomFilter['export']>
dynamicFilter: ReturnType<BloomFilter['export']> dynamicFilter: ReturnType<BloomFilter['export']>
...@@ -56,12 +57,9 @@ export function createClientRouterFilter( ...@@ -56,12 +57,9 @@ export function createClientRouterFilter(
} }
} }
const staticFilter = BloomFilter.from([...staticPaths], POTENTIAL_ERROR_RATE) const staticFilter = BloomFilter.from([...staticPaths], allowedErrorRate)
const dynamicFilter = BloomFilter.from( const dynamicFilter = BloomFilter.from([...dynamicPaths], allowedErrorRate)
[...dynamicPaths],
POTENTIAL_ERROR_RATE
)
const data = { const data = {
staticFilter: staticFilter.export(), staticFilter: staticFilter.export(),
dynamicFilter: dynamicFilter.export(), dynamicFilter: dynamicFilter.export(),
......
...@@ -256,6 +256,9 @@ const configSchema = { ...@@ -256,6 +256,9 @@ const configSchema = {
clientRouterFilterRedirects: { clientRouterFilterRedirects: {
type: 'boolean', type: 'boolean',
}, },
clientRouterFilterAllowedRate: {
type: 'number',
},
cpus: { cpus: {
type: 'number', type: 'number',
}, },
......
...@@ -116,6 +116,10 @@ export interface NextJsWebpackConfig { ...@@ -116,6 +116,10 @@ export interface NextJsWebpackConfig {
export interface ExperimentalConfig { export interface ExperimentalConfig {
clientRouterFilter?: boolean clientRouterFilter?: boolean
clientRouterFilterRedirects?: boolean clientRouterFilterRedirects?: boolean
// decimal for percent for possible false positives
// e.g. 0.01 for 10% potential false matches lower
// percent increases size of the filter
clientRouterFilterAllowedRate?: number
externalMiddlewareRewritesResolve?: boolean externalMiddlewareRewritesResolve?: boolean
extensionAlias?: Record<string, any> extensionAlias?: Record<string, any>
allowedRevalidateHeaderKeys?: string[] allowedRevalidateHeaderKeys?: string[]
......
...@@ -630,7 +630,8 @@ export default class DevServer extends Server { ...@@ -630,7 +630,8 @@ export default class DevServer extends Server {
? ((this.nextConfig as any)._originalRedirects || []).filter( ? ((this.nextConfig as any)._originalRedirects || []).filter(
(r: any) => !r.internal (r: any) => !r.internal
) )
: [] : [],
this.nextConfig.experimental.clientRouterFilterAllowedRate
) )
if ( if (
......
...@@ -1052,7 +1052,12 @@ export default class Router implements BaseRouter { ...@@ -1052,7 +1052,12 @@ export default class Router implements BaseRouter {
return this.change('replaceState', url, as, options) return this.change('replaceState', url, as, options)
} }
async _bfl(as: string, resolvedAs?: string, locale?: string | false) { async _bfl(
as: string,
resolvedAs?: string,
locale?: string | false,
skipNavigate?: boolean
) {
if (process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED) { if (process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED) {
let matchesBflStatic = false let matchesBflStatic = false
let matchesBflDynamic = false let matchesBflDynamic = false
...@@ -1095,6 +1100,9 @@ export default class Router implements BaseRouter { ...@@ -1095,6 +1100,9 @@ export default class Router implements BaseRouter {
// if the client router filter is matched then we trigger // if the client router filter is matched then we trigger
// a hard navigation // a hard navigation
if (matchesBflStatic || matchesBflDynamic) { if (matchesBflStatic || matchesBflDynamic) {
if (skipNavigate) {
return true
}
handleHardNavigation({ handleHardNavigation({
url: addBasePath( url: addBasePath(
addLocale(as, locale || this.locale, this.defaultLocale) addLocale(as, locale || this.locale, this.defaultLocale)
...@@ -1107,6 +1115,7 @@ export default class Router implements BaseRouter { ...@@ -1107,6 +1115,7 @@ export default class Router implements BaseRouter {
} }
} }
} }
return false
} }
private async change( private async change(
...@@ -1311,6 +1320,13 @@ export default class Router implements BaseRouter { ...@@ -1311,6 +1320,13 @@ export default class Router implements BaseRouter {
let parsed = parseRelativeUrl(url) let parsed = parseRelativeUrl(url)
let { pathname, query } = parsed let { pathname, query } = parsed
// if we detected the path as app route during prefetching
// trigger hard navigation
if ((this.components[pathname] as any)?.__appRouter) {
handleHardNavigation({ url, router: this })
return new Promise(() => {})
}
// The build manifest needs to be loaded before auto-static dynamic pages // The build manifest needs to be loaded before auto-static dynamic pages
// get their query parameters to allow ensuring they can be parsed properly // get their query parameters to allow ensuring they can be parsed properly
// when rewritten to // when rewritten to
...@@ -2276,6 +2292,7 @@ export default class Router implements BaseRouter { ...@@ -2276,6 +2292,7 @@ export default class Router implements BaseRouter {
return return
} }
let parsed = parseRelativeUrl(url) let parsed = parseRelativeUrl(url)
const urlPathname = parsed.pathname
let { pathname, query } = parsed let { pathname, query } = parsed
const originalPathname = pathname const originalPathname = pathname
...@@ -2412,6 +2429,10 @@ export default class Router implements BaseRouter { ...@@ -2412,6 +2429,10 @@ export default class Router implements BaseRouter {
const route = removeTrailingSlash(pathname) const route = removeTrailingSlash(pathname)
if (await this._bfl(asPath, resolvedAs, options.locale, true)) {
this.components[urlPathname] = { __appRouter: true } as any
}
await Promise.all([ await Promise.all([
this.pageLoader._isSsg(route).then((isSsg) => { this.pageLoader._isSsg(route).then((isSsg) => {
return isSsg return isSsg
......
...@@ -16,6 +16,24 @@ createNextDescribe( ...@@ -16,6 +16,24 @@ createNextDescribe(
}, },
}, },
({ next, isNextDev: isDev, isNextStart, isNextDeploy }) => { ({ next, isNextDev: isDev, isNextStart, isNextDeploy }) => {
if (!isDev) {
it('should successfully detect app route during prefetch', async () => {
const browser = await next.browser('/')
await check(async () => {
const found = await browser.eval(
'!!window.next.router.components["/dashboard"]'
)
return found
? 'success'
: await browser.eval('Object.keys(window.next.router.components)')
}, 'success')
await browser.elementByCss('a').click()
await browser.waitForElementByCss('#from-dashboard')
})
}
it('should encode chunk path correctly', async () => { it('should encode chunk path correctly', async () => {
await next.fetch('/dynamic-client/first/second') await next.fetch('/dynamic-client/first/second')
const browser = await next.browser('/') const browser = await next.browser('/')
......
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