Unverified Commit 808e558a authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure rewrite query params with middleware are available in router (#37724)

* Ensure rewrite query params with middleware are available in router

* Ensure header matches deploy and add test case

* update check
parent 87d8c2bb
......@@ -1238,13 +1238,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
'x-nextjs-matched-path',
`${query.__nextLocale ? `/${query.__nextLocale}` : ''}${pathname}`
)
// return empty JSON when not an SSG/SSP page and not an error
if (!(isSSG || hasServerProps)) {
res.setHeader('content-type', 'application/json')
res.body('{}')
res.send()
return null
}
}
// Don't delete query.__flight__ yet, it still needs to be used in renderToHTML later
......@@ -1878,6 +1871,23 @@ export default abstract class Server<ServerOptions extends Options = Options> {
}
return response
}
if (
this.router.catchAllMiddleware &&
!!ctx.req.headers['x-nextjs-data'] &&
(!res.statusCode || res.statusCode === 200 || res.statusCode === 404)
) {
res.setHeader(
'x-nextjs-matched-path',
`${query.__nextLocale ? `/${query.__nextLocale}` : ''}${pathname}`
)
res.statusCode = 200
res.setHeader('content-type', 'application/json')
res.body('{}')
res.send()
return null
}
res.statusCode = 404
return this.renderErrorToResponse(ctx, null)
}
......
......@@ -356,6 +356,7 @@ export type CompletePrivateRouteInfo = {
error?: any
route?: string
resolvedAs?: string
query?: ParsedUrlQuery
}
export type AppProps = Pick<CompletePrivateRouteInfo, 'Component' | 'err'> & {
......@@ -1237,6 +1238,7 @@ export default class Router implements BaseRouter {
if ('route' in routeInfo && routeInfo.route !== route) {
pathname = routeInfo.route || route
query = Object.assign({}, routeInfo.query || {}, query)
if (isDynamicRoute(pathname)) {
const prefixedAs =
......@@ -1741,6 +1743,7 @@ export default class Router implements BaseRouter {
routeInfo.props = props
routeInfo.route = route
routeInfo.query = query
routeInfo.resolvedAs = resolvedAs
this.components[route] = routeInfo
......@@ -2171,10 +2174,10 @@ function getMiddlewareData<T extends FetchDataOutput>(
i18n: { locales: options.router.locales },
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
}
const rewriteHeader = response.headers.get('x-nextjs-rewrite')
let rewriteTarget =
response.headers.get('x-nextjs-rewrite') ||
response.headers.get('x-nextjs-matched-path')
rewriteHeader || response.headers.get('x-nextjs-matched-path')
const matchedPath = response.headers.get('x-matched-path')
......@@ -2197,7 +2200,14 @@ function getMiddlewareData<T extends FetchDataOutput>(
]).then(([pages, { __rewrites: rewrites }]: any) => {
let as = parsedRewriteTarget.pathname
if (isDynamicRoute(as)) {
if (
isDynamicRoute(as) ||
(!rewriteHeader &&
pages.includes(
normalizeLocalePath(removeBasePath(as), options.router.locales)
.pathname
))
) {
const parsedSource = getNextPathnameInfo(
parseRelativeUrl(source).pathname,
{ parseData: true }
......@@ -2218,7 +2228,7 @@ function getMiddlewareData<T extends FetchDataOutput>(
if (result.matchedPage) {
parsedRewriteTarget.pathname = result.parsedAs.pathname
parsedRewriteTarget.query = result.parsedAs.query
Object.assign(parsedRewriteTarget.query, result.parsedAs.query)
}
}
......
......@@ -59,11 +59,13 @@ export async function middleware(request) {
if (url.pathname === '/rewrite-to-dynamic') {
url.pathname = '/blog/from-middleware'
url.searchParams.set('some', 'middleware')
return NextResponse.rewrite(url)
}
if (url.pathname === '/rewrite-to-config-rewrite') {
url.pathname = '/rewrite-3'
url.searchParams.set('some', 'middleware')
return NextResponse.rewrite(url)
}
......
......@@ -16,11 +16,11 @@ module.exports = {
return [
{
source: '/rewrite-1',
destination: '/ssr-page',
destination: '/ssr-page?from=config',
},
{
source: '/rewrite-2',
destination: '/about/a',
destination: '/about/a?from=next-config',
},
{
source: '/sha',
......@@ -28,7 +28,7 @@ module.exports = {
},
{
source: '/rewrite-3',
destination: '/blog/middleware-rewrite',
destination: '/blog/middleware-rewrite?hello=config',
},
]
},
......
......@@ -158,6 +158,7 @@ describe('Middleware Runtime', () => {
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({
slug: 'from-middleware',
some: 'middleware',
})
expect(
JSON.parse(await browser.elementByCss('#props').text()).params
......@@ -178,6 +179,8 @@ describe('Middleware Runtime', () => {
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({
slug: 'middleware-rewrite',
hello: 'config',
some: 'middleware',
})
expect(
JSON.parse(await browser.elementByCss('#props').text()).params
......@@ -198,6 +201,7 @@ describe('Middleware Runtime', () => {
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({
slug: 'middleware-rewrite',
hello: 'config',
})
expect(
JSON.parse(await browser.elementByCss('#props').text()).params
......@@ -208,6 +212,18 @@ describe('Middleware Runtime', () => {
expect(await browser.elementByCss('#as-path').text()).toBe('/rewrite-3')
})
it('should have correct route params for rewrite from config non-dynamic route', async () => {
const browser = await webdriver(next.url, '/')
await browser.eval('window.beforeNav = 1')
await browser.eval('window.next.router.push("/rewrite-1")')
await check(() => browser.elementByCss('body').text(), /Hello World/)
expect(await browser.eval('window.next.router.query')).toEqual({
from: 'config',
})
})
it('should redirect the same for direct visit and client-transition', async () => {
const res = await fetchViaHTTP(
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