Unverified Commit 47cb4cf8 authored by kaykdm's avatar kaykdm Committed by GitHub

Fix aspath for getInitialProps (#20572)

Fixes: https://github.com/vercel/next.js/issues/20370

> AsPath is incorrect on Server if you use rewrites and getInitialProps. On the server, asPath is the rewritten asPath while on the client asPath ist as given in the request URL.

The same issue was used to happen on `getServersideProps`, but it was fixed in this PR (https://github.com/vercel/next.js/pull/17121).
`getInitialProps` needs same fix except when the target is serverless, which has correct `asPath` value.

Additional tests have been added in the `getInitialProps` suite to ensure correct asPath with rewrites.
parent 88b6ea41
...@@ -1347,11 +1347,12 @@ export default class Server { ...@@ -1347,11 +1347,12 @@ export default class Server {
typeof components.Component === 'object' && typeof components.Component === 'object' &&
typeof (components.Component as any).renderReqToHTML === 'function' typeof (components.Component as any).renderReqToHTML === 'function'
const isSSG = !!components.getStaticProps const isSSG = !!components.getStaticProps
const isServerProps = !!components.getServerSideProps const hasServerProps = !!components.getServerSideProps
const hasStaticPaths = !!components.getStaticPaths const hasStaticPaths = !!components.getStaticPaths
const hasGetInitialProps = !!(components.Component as any).getInitialProps
// Toggle whether or not this is a Data request // Toggle whether or not this is a Data request
const isDataReq = !!query._nextDataReq && (isSSG || isServerProps) const isDataReq = !!query._nextDataReq && (isSSG || hasServerProps)
delete query._nextDataReq delete query._nextDataReq
// we need to ensure the status code if /404 is visited directly // we need to ensure the status code if /404 is visited directly
...@@ -1379,7 +1380,7 @@ export default class Server { ...@@ -1379,7 +1380,7 @@ export default class Server {
let previewData: string | false | object | undefined let previewData: string | false | object | undefined
let isPreviewMode = false let isPreviewMode = false
if (isServerProps || isSSG) { if (hasServerProps || isSSG) {
previewData = tryGetPreviewData(req, res, this.renderOpts.previewProps) previewData = tryGetPreviewData(req, res, this.renderOpts.previewProps)
isPreviewMode = previewData !== false isPreviewMode = previewData !== false
} }
...@@ -1603,17 +1604,18 @@ export default class Server { ...@@ -1603,17 +1604,18 @@ export default class Server {
locale, locale,
locales, locales,
defaultLocale, defaultLocale,
// For getServerSideProps we need to ensure we use the original URL // For getServerSideProps and getInitialProps we need to ensure we use the original URL
// and not the resolved URL to prevent a hydration mismatch on // and not the resolved URL to prevent a hydration mismatch on
// asPath // asPath
resolvedAsPath: isServerProps resolvedAsPath:
? formatUrl({ hasServerProps || hasGetInitialProps
// we use the original URL pathname less the _next/data prefix if ? formatUrl({
// present // we use the original URL pathname less the _next/data prefix if
pathname: `${urlPathname}${hadTrailingSlash ? '/' : ''}`, // present
query: origQuery, pathname: `${urlPathname}${hadTrailingSlash ? '/' : ''}`,
}) query: origQuery,
: resolvedUrl, })
: resolvedUrl,
} }
renderResult = await renderToHTML( renderResult = await renderToHTML(
...@@ -1720,7 +1722,7 @@ export default class Server { ...@@ -1720,7 +1722,7 @@ export default class Server {
let resHtml = html let resHtml = html
const revalidateOptions = const revalidateOptions =
!this.renderOpts.dev || (isServerProps && !isDataReq) !this.renderOpts.dev || (hasServerProps && !isDataReq)
? { ? {
private: isPreviewMode, private: isPreviewMode,
stateful: !isSSG, stateful: !isSSG,
...@@ -1731,7 +1733,7 @@ export default class Server { ...@@ -1731,7 +1733,7 @@ export default class Server {
if ( if (
!isResSent(res) && !isResSent(res) &&
!isNotFound && !isNotFound &&
(isSSG || isDataReq || isServerProps) (isSSG || isDataReq || hasServerProps)
) { ) {
if (isRedirect && !isDataReq) { if (isRedirect && !isDataReq) {
await handleRedirect(pageData) await handleRedirect(pageData)
......
module.exports = {
// replace me
async rewrites() {
return [
{
source: '/blog/post/:pid',
destination: '/blog/:pid',
},
]
},
}
import React from 'react'
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
return (
<>
<div id="as-path">{router.asPath}</div>
</>
)
}
Post.getInitialProps = () => ({ hello: 'hi' })
export default Post
const page = () => 'hello from sub id'
page.getInitialProps = () => ({ hello: 'hi' })
export default page
export default () => <p id="normal-text">a normal page</p>
import cheerio from 'cheerio'
import { join } from 'path'
import {
findPort,
launchApp,
killApp,
nextStart,
nextBuild,
renderViaHTTP,
File,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 5)
let app
let appPort
const appDir = join(__dirname, '..')
const nextConfig = new File(join(appDir, 'next.config.js'))
const runTests = () => {
it('should have gip in __NEXT_DATA__', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).gip).toBe(true)
})
it('should not have gip in __NEXT_DATA__ for non-GIP page', async () => {
const html = await renderViaHTTP(appPort, '/normal')
const $ = cheerio.load(html)
expect('gip' in JSON.parse($('#__NEXT_DATA__').text())).toBe(false)
})
it('should have correct router.asPath for direct visit dynamic page', async () => {
const html = await renderViaHTTP(appPort, '/blog/1')
const $ = cheerio.load(html)
expect($('#as-path').text()).toBe('/blog/1')
})
it('should have correct router.asPath for direct visit dynamic page rewrite direct', async () => {
const html = await renderViaHTTP(appPort, '/blog/post/1')
const $ = cheerio.load(html)
expect($('#as-path').text()).toBe('/blog/post/1')
})
}
describe('getInitialProps', () => {
describe('dev mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
describe('serverless mode', () => {
beforeAll(async () => {
await nextConfig.replace('// replace me', `target: 'serverless', `)
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
nextConfig.restore()
})
runTests()
})
describe('production mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
})
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