Unverified Commit 2cf1d1c1 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Separate resolved asPath from resolved URL for GSSP (#17121)

This makes sure we have the correct `asPath` value to prevent breaking hydration for `getServerSideProps` pages and doesn't re-use the `resolvedUrl` value for the `asPath` and instead creates a separate `resolvedAsPath` value that only removes the `_next/data` prefix from the path. Additional tests have been added in the `getServerSideProps` suite to ensure correct `asPath` with rewrites. 

Fixes: https://github.com/vercel/next.js/issues/17113
parent 6a4c2564
......@@ -358,22 +358,29 @@ const nextServerlessLoader: loader.Loader = function () {
// We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values
const trustQuery = !getStaticProps && req.headers['${vercelHeader}']
const parsedUrl = handleRewrites(parseUrl(req.url, true))
let parsedUrl = parseUrl(req.url, true)
let routeNoAssetPath = parsedUrl.pathname${
basePath ? `.replace(new RegExp('^${basePath}'), '') || '/'` : ''
}
const origQuery = Object.assign({}, parsedUrl.query)
parsedUrl = handleRewrites(parsedUrl)
${handleBasePath}
if (parsedUrl.pathname.match(/_next\\/data/)) {
const {
default: getRouteFromAssetPath,
default: getrouteNoAssetPath,
} = require('next/dist/next-server/lib/router/utils/get-route-from-asset-path');
_nextData = true;
parsedUrl.pathname = getRouteFromAssetPath(
parsedUrl.pathname = getrouteNoAssetPath(
parsedUrl.pathname.replace(
new RegExp('/_next/data/${escapedBuildId}/'),
'/'
),
'.json'
);
routeNoAssetPath = parsedUrl.pathname
}
const renderOpts = Object.assign(
......@@ -496,8 +503,6 @@ const nextServerlessLoader: loader.Loader = function () {
!fromExport &&
(getStaticProps || getServerSideProps)
) {
const origQuery = parseUrl(req.url, true).query
${
pageIsDynamicRoute
? `
......@@ -519,6 +524,16 @@ const nextServerlessLoader: loader.Loader = function () {
...parsedUrl,
query: origQuery
})
// For getServerSideProps we need to ensure we use the original URL
// and not the resolved URL to prevent a hydration mismatch on asPath
renderOpts.resolvedAsPath = getServerSideProps
? formatUrl({
...parsedUrl,
pathname: routeNoAssetPath,
query: origQuery,
})
: renderOpts.resolvedUrl
}
const isFallback = parsedUrl.query.__nextFallback
......
......@@ -1016,25 +1016,35 @@ export default class Server {
// Compute the iSSG cache key. We use the rewroteUrl since
// pages with fallback: false are allowed to be rewritten to
// and we need to look up the path by the rewritten path
let urlPathname = (req as any)._nextRewroteUrl
let urlPathname = parseUrl(req.url || '').pathname || '/'
let resolvedUrlPathname = (req as any)._nextRewroteUrl
? (req as any)._nextRewroteUrl
: `${parseUrl(req.url || '').pathname!}`
: urlPathname
// remove trailing slash
urlPathname = urlPathname.replace(/(?!^)\/$/, '')
resolvedUrlPathname = removePathTrailingSlash(resolvedUrlPathname)
urlPathname = removePathTrailingSlash(urlPathname)
const stripNextDataPath = (path: string) => {
if (path.includes(this.buildId)) {
path = denormalizePagePath(
(path.split(this.buildId).pop() || '/').replace(/\.json$/, '')
)
}
return path
}
// remove /_next/data prefix from urlPathname so it matches
// for direct page visit and /_next/data visit
if (isDataReq && urlPathname.includes(this.buildId)) {
urlPathname = denormalizePagePath(
(urlPathname.split(this.buildId).pop() || '/').replace(/\.json$/, '')
)
if (isDataReq) {
resolvedUrlPathname = stripNextDataPath(resolvedUrlPathname)
urlPathname = stripNextDataPath(urlPathname)
}
const ssgCacheKey =
isPreviewMode || !isSSG
? undefined // Preview mode bypasses the cache
: `${urlPathname}${query.amp ? '.amp' : ''}`
: `${resolvedUrlPathname}${query.amp ? '.amp' : ''}`
// Complete the response with cached data if its present
const cachedData = ssgCacheKey
......@@ -1107,15 +1117,29 @@ export default class Server {
pageData = renderResult.renderOpts.pageData
sprRevalidate = renderResult.renderOpts.revalidate
} else {
const origQuery = parseUrl(req.url || '', true).query
const resolvedUrl = formatUrl({
pathname: resolvedUrlPathname,
// make sure to only add query values from original URL
query: origQuery,
})
const renderOpts: RenderOpts = {
...components,
...opts,
isDataReq,
resolvedUrl: formatUrl({
pathname: urlPathname,
// make sure to only add query values from original URL
query: parseUrl(req.url || '', true).query,
}),
resolvedUrl,
// For getServerSideProps we need to ensure we use the original URL
// and not the resolved URL to prevent a hydration mismatch on
// asPath
resolvedAsPath: isServerProps
? formatUrl({
// we use the original URL pathname less the _next/data prefix if
// present
pathname: urlPathname,
query: origQuery,
})
: resolvedUrl,
}
renderResult = await renderToHTML(
......@@ -1167,7 +1191,9 @@ export default class Server {
isDynamicPathname &&
// Development should trigger fallback when the path is not in
// `getStaticPaths`
(isProduction || !staticPaths || !staticPaths.includes(urlPathname))
(isProduction ||
!staticPaths ||
!staticPaths.includes(resolvedUrlPathname))
) {
if (
// In development, fall through to render to handle missing
......
......@@ -155,6 +155,7 @@ export type RenderOptsPartial = {
optimizeImages: boolean
devOnlyCacheBusterQueryString?: string
resolvedUrl?: string
resolvedAsPath?: string
}
export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
......@@ -476,7 +477,7 @@ export async function renderToHTML(
: {}),
}
req.url = pathname
renderOpts.resolvedUrl = pathname
renderOpts.resolvedAsPath = pathname
renderOpts.nextExport = true
}
......@@ -490,7 +491,7 @@ export async function renderToHTML(
await Loadable.preloadAll() // Make sure all dynamic imports are loaded
// url will always be set
const asPath: string = renderOpts.resolvedUrl || (req.url as string)
const asPath: string = renderOpts.resolvedAsPath || (req.url as string)
const router = new ServerRouter(
pathname,
query,
......@@ -690,7 +691,7 @@ export async function renderToHTML(
req,
res,
query,
resolvedUrl: asPath,
resolvedUrl: renderOpts.resolvedUrl as string,
...(pageIsDynamic ? { params: params as ParsedUrlQuery } : undefined),
...(previewData !== false
? { preview: true, previewData: previewData }
......
......@@ -24,15 +24,18 @@ export async function getServerSideProps({ params, resolvedUrl }) {
}
export default ({ post, time, params, appProps, resolvedUrl }) => {
const router = useRouter()
return (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<div id="query">{JSON.stringify(router.query)}</div>
<div id="app-query">{JSON.stringify(appProps.query)}</div>
<div id="app-url">{appProps.url}</div>
<div id="resolved-url">{resolvedUrl}</div>
<div id="as-path">{router.asPath}</div>
<Link href="/">
<a id="home">to home</a>
</Link>
......
......@@ -24,6 +24,8 @@ export default ({
appProps,
resolvedUrl,
}) => {
const router = useRouter()
return (
<>
<p>hello: {world}</p>
......@@ -31,10 +33,11 @@ export default ({
<div id="random">{random}</div>
<div id="params">{JSON.stringify(params)}</div>
<div id="initial-query">{JSON.stringify(query)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<div id="query">{JSON.stringify(router.query)}</div>
<div id="app-query">{JSON.stringify(appProps.query)}</div>
<div id="app-url">{appProps.url}</div>
<div id="resolved-url">{resolvedUrl}</div>
<div id="as-path">{router.asPath}</div>
<Link href="/">
<a id="home">to home</a>
</Link>
......
......@@ -360,6 +360,7 @@ const runTests = (dev = false) => {
expect($('#app-url').text()).toContain('/blog/post-1')
expect(JSON.parse($('#app-query').text())).toEqual({ post: 'post-1' })
expect($('#resolved-url').text()).toBe('/blog/post-1')
expect($('#as-path').text()).toBe('/blog/post-1')
})
it('should have correct req.url and query for direct visit dynamic page rewrite direct', async () => {
......@@ -368,6 +369,7 @@ const runTests = (dev = false) => {
expect($('#app-url').text()).toContain('/blog-post-1')
expect(JSON.parse($('#app-query').text())).toEqual({ post: 'post-1' })
expect($('#resolved-url').text()).toBe('/blog/post-1')
expect($('#as-path').text()).toBe('/blog-post-1')
})
it('should have correct req.url and query for direct visit dynamic page rewrite direct with internal query', async () => {
......@@ -379,6 +381,7 @@ const runTests = (dev = false) => {
hello: 'world',
})
expect($('#resolved-url').text()).toBe('/blog/post-2')
expect($('#as-path').text()).toBe('/blog-post-2')
})
it('should have correct req.url and query for direct visit dynamic page rewrite param', async () => {
......@@ -390,6 +393,7 @@ const runTests = (dev = false) => {
param: 'post-3',
})
expect($('#resolved-url').text()).toBe('/blog/post-3')
expect($('#as-path').text()).toBe('/blog-post-3')
})
it('should have correct req.url and query for direct visit dynamic page with query', async () => {
......@@ -403,6 +407,7 @@ const runTests = (dev = false) => {
hello: 'world',
})
expect($('#resolved-url').text()).toBe('/blog/post-1?hello=world')
expect($('#as-path').text()).toBe('/blog/post-1?hello=world')
})
it('should have correct req.url and query for direct visit', async () => {
......@@ -411,6 +416,7 @@ const runTests = (dev = false) => {
expect($('#app-url').text()).toContain('/something')
expect(JSON.parse($('#app-query').text())).toEqual({})
expect($('#resolved-url').text()).toBe('/something')
expect($('#as-path').text()).toBe('/something')
})
it('should return data correctly', async () => {
......
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