Unverified Commit cba7070c authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Added support for query params on not found pages (#43836)

Previously, query parameters were not available on 404 pages because
calling the router methods would change the pathname in the browser.
This change adds support for the query to update for those pages without
updating the path to include the basePath.

This additionally narrows some Typescript types that were previous set
to `any` which highlighted some type errors that were corrected.

Fixes: https://github.com/vercel/next.js/issues/35990Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent f012eab0
...@@ -116,11 +116,6 @@ class Container extends React.Component<{ ...@@ -116,11 +116,6 @@ class Container extends React.Component<{
// - if rewrites in next.config.js match (may have rewrite params) // - if rewrites in next.config.js match (may have rewrite params)
if ( if (
router.isSsr && router.isSsr &&
// We don't update for 404 requests as this can modify
// the asPath unexpectedly e.g. adding basePath when
// it wasn't originally present
initialData.page !== '/404' &&
initialData.page !== '/_error' &&
(initialData.isFallback || (initialData.isFallback ||
(initialData.nextExport && (initialData.nextExport &&
(isDynamicRoute(router.pathname) || (isDynamicRoute(router.pathname) ||
......
This diff is collapsed.
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import Debug from './debug'
function transform(router) {
return {
pathname: router.pathname,
asPath: router.asPath,
query: Object.entries(router.query)
.map(([key, value]) => [key, value].join('='))
.join('&'),
isReady: router.isReady ? 'true' : 'false',
}
}
export default function DebugError({ children }) {
const router = useRouter()
const [debug, setDebug] = useState({})
useEffect(() => {
setDebug(transform(router))
}, [router])
return (
<>
<dl>
<Debug name="pathname" value={debug.pathname} />
<Debug name="asPath" value={debug.asPath} />
<Debug name="query" value={debug.query} />
<Debug name="isReady" value={debug.isReady} />
</dl>
{children}
</>
)
}
export default function Debug({ name, value }) {
return (
<>
<dt>{name}</dt>
<dd id={name}>{value}</dd>
</>
)
}
import { NextResponse } from 'next/server'
export function middleware() {
return NextResponse.next()
}
import DebugError from '../components/debug-error'
export default function Custom404() {
return <DebugError />
}
import DebugError from '../components/debug-error'
function Error({ statusCode }) {
return <DebugError />
}
Error.getInitialProps = ({ res, err }) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404
return { statusCode }
}
export default Error
export default function Page() {
throw new Error('there was an error')
}
export const getServerSideProps = () => {
return { props: {} }
}
import { createNext, FileRef } from 'e2e-utils'
import path from 'path'
import { type NextInstance } from 'test/lib/next-modes/base'
import webdriver from 'next-webdriver'
import { type NextConfig } from 'next'
const pathnames = {
'/404': ['/not/a/real/page?with=query', '/not/a/real/page'],
// Special handling is done for the error cases because these need to be
// prefixed with the basePath if it's enabled for that test suite. These also
// should only run when the application is tested in production.
'/_error': ['/error?with=query', '/error'],
}
const basePath = '/docs'
const i18n = { defaultLocale: 'en-ca', locales: ['en-ca', 'en-fr'] }
const table = [
{ basePath: false, i18n: true, middleware: false },
{ basePath: true, i18n: false, middleware: false },
{ basePath: true, i18n: true, middleware: false },
{ basePath: false, i18n: false, middleware: false },
{ basePath: false, i18n: false, middleware: true },
]
describe.each(table)(
'404-page-router with basePath of $basePath and i18n of $i18n and middleware $middleware',
(options) => {
const isDev = (global as any).isNextDev
let next: NextInstance
let nextConfig: NextConfig
beforeAll(async () => {
const files = {
pages: new FileRef(path.join(__dirname, 'app/pages')),
components: new FileRef(path.join(__dirname, 'app/components')),
}
// Only add in the middleware if we're testing with middleware enabled.
if (options.middleware) {
files['middleware.js'] = new FileRef(
path.join(__dirname, 'app/middleware.js')
)
}
nextConfig = {}
if (options.basePath) nextConfig.basePath = basePath
if (options.i18n) nextConfig.i18n = i18n
next = await createNext({ files, nextConfig })
})
afterAll(() => next.destroy())
/**
* translate will iterate over the pathnames and generate the test cases
* used in the following table test.
*
* @param pathname key for the pathname to iterate over
* @param shouldPrefixPathname true if the url's should be prefixed with the basePath
* @returns test cases
*/
function translate(
pathname: keyof typeof pathnames,
shouldPrefixPathname: boolean = false
): { url: string; pathname: keyof typeof pathnames; asPath: string }[] {
return pathnames[pathname].map((asPath) => ({
// Prefix the request URL with the basePath if enabled.
url: shouldPrefixPathname ? basePath + asPath : asPath,
// The pathname is not prefixed with the basePath.
pathname,
// The asPath is not prefixed with the basePath.
asPath,
}))
}
// Always include the /404 tests, they'll run the same in development and
// production environments.
const urls = translate('/404')
// Only include the /_error tests in production because in development we
// have the error overlay.
if (!isDev) {
urls.push(...translate('/_error', options.basePath))
}
describe.each(urls)('for $url', ({ url, pathname, asPath }) => {
it('should have the correct router parameters after it is ready', async () => {
const query = url.split('?')[1] ?? ''
const browser = await webdriver(next.url, url)
try {
await browser.waitForCondition(
'document.getElementById("isReady")?.innerText === "true"'
)
expect(await browser.elementById('pathname').text()).toEqual(pathname)
expect(await browser.elementById('asPath').text()).toEqual(asPath)
expect(await browser.elementById('query').text()).toEqual(query)
} finally {
await browser.close()
}
})
})
}
)
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