Unverified Commit 89bc9c66 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure resolvedUrl is correct with fallback rewrites (#37932)

* Ensure resolvedUrl is correct with fallback rewrites

* fix-lint

* normalize slash
parent b04cdc9f
...@@ -28,6 +28,7 @@ import { denormalizePagePath } from '../../../../shared/lib/page-path/denormaliz ...@@ -28,6 +28,7 @@ import { denormalizePagePath } from '../../../../shared/lib/page-path/denormaliz
import cookie from 'next/dist/compiled/cookie' import cookie from 'next/dist/compiled/cookie'
import { TEMPORARY_REDIRECT_STATUS } from '../../../../shared/lib/constants' import { TEMPORARY_REDIRECT_STATUS } from '../../../../shared/lib/constants'
import { addRequestMeta } from '../../../../server/request-meta' import { addRequestMeta } from '../../../../server/request-meta'
import { removeTrailingSlash } from '../../../../shared/lib/router/utils/remove-trailing-slash'
export const vercelHeader = 'x-vercel-id' export const vercelHeader = 'x-vercel-id'
...@@ -98,7 +99,11 @@ export function getUtils({ ...@@ -98,7 +99,11 @@ export function getUtils({
let fsPathname = parsedUrl.pathname let fsPathname = parsedUrl.pathname
const matchesPage = () => { const matchesPage = () => {
return fsPathname === page || dynamicRouteMatcher?.(fsPathname) const fsPathnameNoSlash = removeTrailingSlash(fsPathname || '')
return (
fsPathnameNoSlash === removeTrailingSlash(page) ||
dynamicRouteMatcher?.(fsPathnameNoSlash)
)
} }
const checkRewrite = (rewrite: Rewrite): boolean => { const checkRewrite = (rewrite: Rewrite): boolean => {
......
...@@ -1341,6 +1341,11 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1341,6 +1341,11 @@ export default abstract class Server<ServerOptions extends Options = Options> {
let resolvedUrlPathname = let resolvedUrlPathname =
getRequestMeta(req, '_nextRewroteUrl') || urlPathname getRequestMeta(req, '_nextRewroteUrl') || urlPathname
if (isSSG && this.minimalMode && req.headers['x-matched-path']) {
// the url value is already correct when the matched-path header is set
resolvedUrlPathname = urlPathname
}
urlPathname = removeTrailingSlash(urlPathname) urlPathname = removeTrailingSlash(urlPathname)
resolvedUrlPathname = normalizeLocalePath( resolvedUrlPathname = normalizeLocalePath(
removeTrailingSlash(resolvedUrlPathname), removeTrailingSlash(resolvedUrlPathname),
......
module.exports = {
experimental: {
outputStandalone: true,
},
trailingSlash: true,
rewrites() {
return {
beforeFiles: [
{
source: '/news/:path/',
destination: '/news/:path*/',
},
],
afterFiles: [
{
source: '/somewhere',
destination: '/',
},
],
fallback: [
{
source: '/:path*',
destination: '/:path*',
},
{
source: '/(.*)',
destination: '/seo-redirects',
},
],
}
},
}
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="page">/blog/[slug]</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="asPath">{router.asPath}</p>
<p id="pathname">{router.pathname}</p>
<p id="query">{JSON.stringify(router.query)}</p>
</>
)
}
export function getStaticProps({ params }) {
console.log('getStaticProps /blog/[slug]', params)
return {
props: {
params,
now: Date.now(),
},
}
}
export function getStaticPaths() {
return {
paths: ['/blog/first'],
fallback: 'blocking',
}
}
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="page">/</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="asPath">{router.asPath}</p>
<p id="pathname">{router.pathname}</p>
<p id="query">{JSON.stringify(router.query)}</p>
</>
)
}
export function getStaticProps() {
console.log('getStaticProps /')
return {
props: {
index: true,
now: Date.now(),
},
}
}
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="page">/news</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="asPath">{router.asPath}</p>
<p id="pathname">{router.pathname}</p>
<p id="query">{JSON.stringify(router.query)}</p>
</>
)
}
export function getStaticProps() {
console.log('getStaticProps /news')
return {
props: {
news: true,
now: Date.now(),
},
}
}
import glob from 'glob'
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import {
killApp,
findPort,
renderViaHTTP,
initNextServerScript,
} from 'next-test-utils'
describe('minimal-mode-response-cache', () => {
let next: NextInstance
let server
let appPort
beforeAll(async () => {
// test build against environment with next support
process.env.NOW_BUILDER = '1'
next = await createNext({
files: new FileRef(join(__dirname, 'app')),
})
await next.stop()
await fs.move(
join(next.testDir, '.next/standalone'),
join(next.testDir, 'standalone')
)
for (const file of await fs.readdir(next.testDir)) {
if (file !== 'standalone') {
await fs.remove(join(next.testDir, file))
console.log('removed', file)
}
}
const files = glob.sync('**/*', {
cwd: join(next.testDir, 'standalone/.next/server/pages'),
dot: true,
})
for (const file of files) {
if (file.endsWith('.json') || file.endsWith('.html')) {
await fs.remove(join(next.testDir, '.next/server', file))
}
}
const testServer = join(next.testDir, 'standalone/server.js')
await fs.writeFile(
testServer,
(await fs.readFile(testServer, 'utf8'))
.replace('console.error(err)', `console.error('top-level', err)`)
.replace('conf:', 'minimalMode: true,conf:')
)
appPort = await findPort()
server = await initNextServerScript(
testServer,
/Listening on/,
{
...process.env,
PORT: appPort,
},
undefined,
{
cwd: next.testDir,
}
)
})
afterAll(async () => {
await next.destroy()
if (server) await killApp(server)
})
it('should have correct responses', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html.length).toBeTruthy()
for (const { path, matchedPath, query, asPath, pathname } of [
{ path: '/', asPath: '/' },
{ path: '/', matchedPath: '/index', asPath: '/' },
{ path: '/', matchedPath: '/index/', asPath: '/' },
{ path: '/', matchedPath: '/', asPath: '/' },
{
path: '/news/',
matchedPath: '/news/',
asPath: '/news/',
pathname: '/news',
},
{
path: '/news/',
matchedPath: '/news',
asPath: '/news/',
pathname: '/news',
},
{
path: '/blog/first/',
matchedPath: '/blog/first/',
pathname: '/blog/[slug]',
asPath: '/blog/first/',
query: { slug: 'first' },
},
{
path: '/blog/second/',
matchedPath: '/blog/[slug]/',
pathname: '/blog/[slug]',
asPath: '/blog/second/',
query: { slug: 'second' },
},
]) {
const html = await renderViaHTTP(appPort, path, undefined, {
headers: {
'x-matched-path': matchedPath || path,
},
})
const $ = cheerio.load(html)
expect($('#asPath').text()).toBe(asPath)
expect($('#pathname').text()).toBe(pathname || path)
expect(JSON.parse($('#query').text())).toEqual(query || {})
}
})
})
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