Unverified Commit 7e7d7bbc authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Fix incorrect asPath with fallback rewrite in minimal mode (#36463)

This continues off of the change in https://github.com/vercel/next.js/pull/36368 and ensures a fallback rewrite does not influence the `asPath` as these are only matched when a filesystem or dynamic route aren't matched. 

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

x-ref: https://github.com/vercel/next.js/pull/36368
parent d5e767b2
...@@ -105,19 +105,15 @@ const nextServerlessLoader: webpack.loader.Loader = function () { ...@@ -105,19 +105,15 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
import { getApiHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/api-handler' import { getApiHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/api-handler'
const combinedRewrites = Array.isArray(routesManifest.rewrites) const rewrites = Array.isArray(routesManifest.rewrites)
? routesManifest.rewrites ? {
: [] afterFiles: routesManifest.rewrites
if (!Array.isArray(routesManifest.rewrites)) {
combinedRewrites.push(...routesManifest.rewrites.beforeFiles)
combinedRewrites.push(...routesManifest.rewrites.afterFiles)
combinedRewrites.push(...routesManifest.rewrites.fallback)
} }
: routesManifest.rewrites
const apiHandler = getApiHandler({ const apiHandler = getApiHandler({
pageModule: require(${stringifyRequest(this, absolutePagePath)}), pageModule: require(${stringifyRequest(this, absolutePagePath)}),
rewrites: combinedRewrites, rewrites: rewrites,
i18n: ${i18n || 'undefined'}, i18n: ${i18n || 'undefined'},
page: "${page}", page: "${page}",
basePath: "${basePath}", basePath: "${basePath}",
...@@ -166,15 +162,11 @@ const nextServerlessLoader: webpack.loader.Loader = function () { ...@@ -166,15 +162,11 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
export let config = compMod['confi' + 'g'] || (compMod.then && compMod.then(mod => mod['confi' + 'g'])) || {} export let config = compMod['confi' + 'g'] || (compMod.then && compMod.then(mod => mod['confi' + 'g'])) || {}
export const _app = App export const _app = App
const combinedRewrites = Array.isArray(routesManifest.rewrites) const rewrites = Array.isArray(routesManifest.rewrites)
? routesManifest.rewrites ? {
: [] afterFiles: routesManifest.rewrites
if (!Array.isArray(routesManifest.rewrites)) {
combinedRewrites.push(...routesManifest.rewrites.beforeFiles)
combinedRewrites.push(...routesManifest.rewrites.afterFiles)
combinedRewrites.push(...routesManifest.rewrites.fallback)
} }
: routesManifest.rewrites
const { renderReqToHTML, render } = getPageHandler({ const { renderReqToHTML, render } = getPageHandler({
pageModule: compMod, pageModule: compMod,
...@@ -202,7 +194,7 @@ const nextServerlessLoader: webpack.loader.Loader = function () { ...@@ -202,7 +194,7 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
buildManifest, buildManifest,
reactLoadableManifest, reactLoadableManifest,
rewrites: combinedRewrites, rewrites: rewrites,
i18n: ${i18n || 'undefined'}, i18n: ${i18n || 'undefined'},
page: "${page}", page: "${page}",
buildId: "${buildId}", buildId: "${buildId}",
......
...@@ -51,7 +51,11 @@ export type ServerlessHandlerCtx = { ...@@ -51,7 +51,11 @@ export type ServerlessHandlerCtx = {
buildManifest?: BuildManifest buildManifest?: BuildManifest
reactLoadableManifest?: any reactLoadableManifest?: any
basePath: string basePath: string
rewrites: Rewrite[] rewrites: {
fallback?: Rewrite[]
afterFiles?: Rewrite[]
beforeFiles?: Rewrite[]
}
pageIsDynamic: boolean pageIsDynamic: boolean
generateEtags: boolean generateEtags: boolean
distDir: string distDir: string
...@@ -92,8 +96,13 @@ export function getUtils({ ...@@ -92,8 +96,13 @@ export function getUtils({
parsedUrl: UrlWithParsedQuery parsedUrl: UrlWithParsedQuery
) { ) {
const rewriteParams = {} const rewriteParams = {}
let fsPathname = parsedUrl.pathname
for (const rewrite of rewrites) { const matchesPage = () => {
return fsPathname === page || dynamicRouteMatcher?.(fsPathname)
}
const checkRewrite = (rewrite: Rewrite): boolean => {
const matcher = getCustomRouteMatcher(rewrite.source) const matcher = getCustomRouteMatcher(rewrite.source)
let params = matcher(parsedUrl.pathname) let params = matcher(parsedUrl.pathname)
...@@ -115,13 +124,18 @@ export function getUtils({ ...@@ -115,13 +124,18 @@ export function getUtils({
query: parsedUrl.query, query: parsedUrl.query,
}) })
// if the rewrite destination is external break rewrite chain
if (parsedDestination.protocol) {
return true
}
Object.assign(rewriteParams, destQuery, params) Object.assign(rewriteParams, destQuery, params)
Object.assign(parsedUrl.query, parsedDestination.query) Object.assign(parsedUrl.query, parsedDestination.query)
delete (parsedDestination as any).query delete (parsedDestination as any).query
Object.assign(parsedUrl, parsedDestination) Object.assign(parsedUrl, parsedDestination)
let fsPathname = parsedUrl.pathname fsPathname = parsedUrl.pathname
if (basePath) { if (basePath) {
fsPathname = fsPathname =
...@@ -139,7 +153,7 @@ export function getUtils({ ...@@ -139,7 +153,7 @@ export function getUtils({
} }
if (fsPathname === page) { if (fsPathname === page) {
break return true
} }
if (pageIsDynamic && dynamicRouteMatcher) { if (pageIsDynamic && dynamicRouteMatcher) {
...@@ -149,12 +163,32 @@ export function getUtils({ ...@@ -149,12 +163,32 @@ export function getUtils({
...parsedUrl.query, ...parsedUrl.query,
...dynamicParams, ...dynamicParams,
} }
break return true
} }
} }
} }
return false
}
for (const rewrite of rewrites.beforeFiles || []) {
checkRewrite(rewrite)
} }
if (fsPathname !== page) {
let finished = false
for (const rewrite of rewrites.afterFiles || []) {
finished = checkRewrite(rewrite)
if (finished) break
}
if (!finished && !matchesPage()) {
for (const rewrite of rewrites.fallback || []) {
finished = checkRewrite(rewrite)
if (finished) break
}
}
}
return rewriteParams return rewriteParams
} }
......
...@@ -8,7 +8,6 @@ import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plu ...@@ -8,7 +8,6 @@ import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plu
import type { NextConfig, NextConfigComplete } from './config-shared' import type { NextConfig, NextConfigComplete } from './config-shared'
import type { NextParsedUrlQuery, NextUrlWithParsedQuery } from './request-meta' import type { NextParsedUrlQuery, NextUrlWithParsedQuery } from './request-meta'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { Rewrite } from '../lib/load-custom-routes'
import type { RenderOpts, RenderOptsPartial } from './render' import type { RenderOpts, RenderOptsPartial } from './render'
import type { ResponseCacheEntry, ResponseCacheValue } from './response-cache' import type { ResponseCacheEntry, ResponseCacheValue } from './response-cache'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
...@@ -479,19 +478,22 @@ export default abstract class Server { ...@@ -479,19 +478,22 @@ export default abstract class Server {
srcPathname = denormalizePagePath(srcPathname) srcPathname = denormalizePagePath(srcPathname)
} }
const pageIsDynamic = isDynamicRoute(srcPathname) if (!isDynamicRoute(srcPathname) && !this.hasPage(srcPathname)) {
const combinedRewrites: Rewrite[] = [] for (const dynamicRoute of this.dynamicRoutes || []) {
if (dynamicRoute.match(srcPathname)) {
combinedRewrites.push(...this.customRoutes.rewrites.beforeFiles) srcPathname = dynamicRoute.page
combinedRewrites.push(...this.customRoutes.rewrites.afterFiles) break
combinedRewrites.push(...this.customRoutes.rewrites.fallback) }
}
}
const pageIsDynamic = isDynamicRoute(srcPathname)
const utils = getUtils({ const utils = getUtils({
pageIsDynamic, pageIsDynamic,
page: srcPathname, page: srcPathname,
i18n: this.nextConfig.i18n, i18n: this.nextConfig.i18n,
basePath: this.nextConfig.basePath, basePath: this.nextConfig.basePath,
rewrites: combinedRewrites, rewrites: this.customRoutes.rewrites,
}) })
try { try {
......
...@@ -49,7 +49,15 @@ describe('should set-up next', () => { ...@@ -49,7 +49,15 @@ describe('should set-up next', () => {
outputStandalone: true, outputStandalone: true,
}, },
async rewrites() { async rewrites() {
return [ return {
beforeFiles: [],
fallback: [
{
source: '/an-ssg-path',
destination: '/hello.txt',
},
],
afterFiles: [
{ {
source: '/some-catch-all/:path*', source: '/some-catch-all/:path*',
destination: '/', destination: '/',
...@@ -62,7 +70,8 @@ describe('should set-up next', () => { ...@@ -62,7 +70,8 @@ describe('should set-up next', () => {
source: '/to-dynamic/:path', source: '/to-dynamic/:path',
destination: '/dynamic/:path', destination: '/dynamic/:path',
}, },
] ],
}
}, },
}, },
}) })
...@@ -691,6 +700,7 @@ describe('should set-up next', () => { ...@@ -691,6 +700,7 @@ describe('should set-up next', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const $ = cheerio.load(await res.text()) const $ = cheerio.load(await res.text())
expect($('#resolved-url').text()).toBe('/dynamic/post-2') expect($('#resolved-url').text()).toBe('/dynamic/post-2')
expect(JSON.parse($('#router').text()).asPath).toBe('/to-dynamic/post-2')
}) })
it('should have correct resolvedUrl from dynamic route', async () => { it('should have correct resolvedUrl from dynamic route', async () => {
...@@ -876,6 +886,20 @@ describe('should set-up next', () => { ...@@ -876,6 +886,20 @@ describe('should set-up next', () => {
expect($('#slug-page').text()).toBe('[slug] page') expect($('#slug-page').text()).toBe('[slug] page')
}) })
it('should have correct asPath on dynamic SSG page correctly', async () => {
const res = await fetchViaHTTP(appPort, '/an-ssg-path', undefined, {
headers: {
'x-matched-path': '/[slug]',
},
redirect: 'manual',
})
const html = await res.text()
const $ = cheerio.load(html)
expect($('#slug-page').text()).toBe('[slug] page')
expect(JSON.parse($('#router').text()).asPath).toBe('/an-ssg-path')
})
it('should copy and read .env file', async () => { it('should copy and read .env file', async () => {
const res = await fetchViaHTTP(appPort, '/api/env') const res = await fetchViaHTTP(appPort, '/api/env')
......
import { useRouter } from 'next/router'
export const getStaticProps = () => { export const getStaticProps = () => {
return { return {
props: { props: {
...@@ -14,5 +16,11 @@ export const getStaticPaths = () => { ...@@ -14,5 +16,11 @@ export const getStaticPaths = () => {
} }
export default function Page(props) { export default function Page(props) {
return <p id="slug-page">[slug] page</p> const router = useRouter()
return (
<>
<p id="slug-page">[slug] page</p>
<p id="router">{JSON.stringify(router)}</p>
</>
)
} }
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