Skip to content

Commit

Permalink
Ensure middleware has single data fetch on query hydration with valid…
Browse files Browse the repository at this point in the history
… props (#39210)

* Ensure middleware has single data fetch on query hydration with valid props

* re-add check

* fix redirect case
  • Loading branch information
ijjk committed Aug 2, 2022
1 parent c4e8d7d commit cd3e054
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 23 deletions.
42 changes: 19 additions & 23 deletions packages/next/shared/lib/router/router.ts
Expand Up @@ -427,7 +427,7 @@ const backgroundCache: Record<string, Promise<any>> = {}

interface FetchDataOutput {
dataHref: string
json: Record<string, any>
json: Record<string, any> | null
response: Response
text: string
}
Expand Down Expand Up @@ -508,7 +508,7 @@ function fetchNextData({

return {
dataHref,
json: parseJSON ? tryToParseAsJSON(text) : {},
json: parseJSON ? tryToParseAsJSON(text) : null,
response,
text,
}
Expand Down Expand Up @@ -552,7 +552,7 @@ function tryToParseAsJSON(text: string) {
try {
return JSON.parse(text)
} catch (error) {
return {}
return null
}
}

Expand Down Expand Up @@ -1807,28 +1807,24 @@ export default class Router implements BaseRouter {

const { props } = await this._getData(async () => {
if (shouldFetchData && !useStreamedFlightData) {
const { json } =
data?.json &&
data?.response.headers
.get('content-type')
?.includes('application/json')
? data
: await fetchNextData({
dataHref: this.pageLoader.getDataHref({
href: formatWithValidation({ pathname, query }),
asPath: resolvedAs,
locale,
}),
isServerRender: this.isSsr,
parseJSON: true,
inflightCache: this.sdc,
persistCache: !isPreview,
isPrefetch: false,
unstable_skipClientCache,
})
const { json } = data?.json
? data
: await fetchNextData({
dataHref: this.pageLoader.getDataHref({
href: formatWithValidation({ pathname, query }),
asPath: resolvedAs,
locale,
}),
isServerRender: this.isSsr,
parseJSON: true,
inflightCache: this.sdc,
persistCache: !isPreview,
isPrefetch: false,
unstable_skipClientCache,
})

return {
props: json,
props: json || {},
}
}

Expand Down
21 changes: 21 additions & 0 deletions test/e2e/middleware-rewrites/test/index.test.ts
Expand Up @@ -27,6 +27,27 @@ describe('Middleware Rewrite', () => {
testsWithLocale('/fr')

function tests() {
it('should not have un-necessary data request on rewrite', async () => {
const browser = await webdriver(next.url, '/to-blog/first', {
waitHydration: false,
})
let requests = []

browser.on('request', (req) => {
requests.push(new URL(req.url()).pathname)
})

await check(
() => browser.eval(`next.router.isReady ? "yup" : "nope"`),
'yup'
)

expect(
requests.filter((url) => url === '/fallback-true-blog/first.json')
.length
).toBeLessThan(2)
})

it('should not mix component cache when navigating between dynamic routes', async () => {
const browser = await webdriver(next.url, '/param-1')

Expand Down

0 comments on commit cd3e054

Please sign in to comment.