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