Unverified Commit 3e9a99c8 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Fix middleware notFound: true handling (#46759)

This ensures we properly handle rendering the `404` page when `notFound:
true` is returned and middleware is present.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

Fixes: https://github.com/vercel/next.js/issues/38239
x-ref: https://github.com/vercel/next.js/issues/43772

---------
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 6357de01
...@@ -535,7 +535,7 @@ function fetchNextData({ ...@@ -535,7 +535,7 @@ function fetchNextData({
return { dataHref, response, text, json: {}, cacheKey } return { dataHref, response, text, json: {}, cacheKey }
} }
if (!hasMiddleware && response.status === 404) { if (response.status === 404) {
if (tryToParseAsJSON(text)?.notFound) { if (tryToParseAsJSON(text)?.notFound) {
return { return {
dataHref, dataHref,
...@@ -1647,6 +1647,7 @@ export default class Router implements BaseRouter { ...@@ -1647,6 +1647,7 @@ export default class Router implements BaseRouter {
routeProps: { shallow: false }, routeProps: { shallow: false },
locale: nextState.locale, locale: nextState.locale,
isPreview: nextState.isPreview, isPreview: nextState.isPreview,
isNotFound: true,
}) })
if ('type' in routeInfo) { if ('type' in routeInfo) {
...@@ -1913,6 +1914,7 @@ export default class Router implements BaseRouter { ...@@ -1913,6 +1914,7 @@ export default class Router implements BaseRouter {
unstable_skipClientCache, unstable_skipClientCache,
isQueryUpdating, isQueryUpdating,
isMiddlewareRewrite, isMiddlewareRewrite,
isNotFound,
}: { }: {
route: string route: string
pathname: string pathname: string
...@@ -1926,6 +1928,7 @@ export default class Router implements BaseRouter { ...@@ -1926,6 +1928,7 @@ export default class Router implements BaseRouter {
unstable_skipClientCache?: boolean unstable_skipClientCache?: boolean
isQueryUpdating?: boolean isQueryUpdating?: boolean
isMiddlewareRewrite?: boolean isMiddlewareRewrite?: boolean
isNotFound?: boolean
}) { }) {
/** /**
* This `route` binding can change if there's a rewrite * This `route` binding can change if there's a rewrite
...@@ -1959,7 +1962,7 @@ export default class Router implements BaseRouter { ...@@ -1959,7 +1962,7 @@ export default class Router implements BaseRouter {
dataHref: this.pageLoader.getDataHref({ dataHref: this.pageLoader.getDataHref({
href: formatWithValidation({ pathname, query }), href: formatWithValidation({ pathname, query }),
skipInterpolation: true, skipInterpolation: true,
asPath: resolvedAs, asPath: isNotFound ? '/404' : resolvedAs,
locale, locale,
}), }),
hasMiddleware: true, hasMiddleware: true,
...@@ -1981,7 +1984,7 @@ export default class Router implements BaseRouter { ...@@ -1981,7 +1984,7 @@ export default class Router implements BaseRouter {
? null ? null
: await withMiddlewareEffects({ : await withMiddlewareEffects({
fetchData: () => fetchNextData(fetchNextDataParams), fetchData: () => fetchNextData(fetchNextDataParams),
asPath: resolvedAs, asPath: isNotFound ? '/404' : resolvedAs,
locale: locale, locale: locale,
router: this, router: this,
}).catch((err) => { }).catch((err) => {
...@@ -1995,6 +1998,12 @@ export default class Router implements BaseRouter { ...@@ -1995,6 +1998,12 @@ export default class Router implements BaseRouter {
throw err throw err
}) })
// when rendering error routes we don't apply middleware
// effects
if (data && (pathname === '/_error' || pathname === '/404')) {
data.effect = undefined
}
if (isQueryUpdating) { if (isQueryUpdating) {
if (!data) { if (!data) {
data = { json: self.__NEXT_DATA__.props } data = { json: self.__NEXT_DATA__.props }
......
...@@ -8,6 +8,11 @@ export default function Page(props) { ...@@ -8,6 +8,11 @@ export default function Page(props) {
router.isReady ? router.asPath : router.href router.isReady ? router.asPath : router.href
) )
if (!props.params) {
console.error('props', props)
throw new Error('missing props!!!')
}
useEffect(() => { useEffect(() => {
if (router.isReady) { if (router.isReady) {
setAsPath(router.asPath) setAsPath(router.asPath)
...@@ -26,6 +31,12 @@ export default function Page(props) { ...@@ -26,6 +31,12 @@ export default function Page(props) {
} }
export function getStaticProps({ params }) { export function getStaticProps({ params }) {
if (params.slug.includes('not-found')) {
return {
notFound: true,
}
}
return { return {
props: { props: {
now: Date.now(), now: Date.now(),
......
...@@ -70,6 +70,18 @@ describe('Middleware Runtime', () => { ...@@ -70,6 +70,18 @@ describe('Middleware Runtime', () => {
} }
function runTests({ i18n }: { i18n?: boolean }) { function runTests({ i18n }: { i18n?: boolean }) {
it('should work with notFound: true correctly', async () => {
const browser = await next.browser('/ssr-page')
await browser.eval('window.beforeNav = 1')
await browser.eval('window.next.router.push("/ssg/not-found-1")')
await check(
() => browser.eval('document.documentElement.innerHTML'),
/This page could not be found/
)
expect(await browser.eval('window.beforeNav')).toBe(1)
})
it('should be able to rewrite on _next/static/chunks/pages/ 404', async () => { it('should be able to rewrite on _next/static/chunks/pages/ 404', async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
next.url, next.url,
......
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