Unverified Commit 35a3eca3 authored by Sam Ko's avatar Sam Ko Committed by GitHub

fix: uri encode dynamic routes in dev (#71588)

## Why?

In `next dev`, `404` errors are returned for dynamic routes that contain
characters that should be URI encoded in the path. The `404`s are not
present in `next build`.

## How?

We're failing to decode the
[`resolvedUrlPathname`](https://github.com/vercel/next.js/blob/ffec1d3a458056a4531e6b35518fca28bf9c3943/packages/next/src/server/base-server.ts#L2897)
in `next dev`, resulting in a `404`. So we add the same decoding logic
in development.

- Fixes https://github.com/vercel/next.js/issues/63002
parent e84b65b0
......@@ -85,7 +85,6 @@ import RenderResult from './render-result'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import * as Log from '../build/output/log'
import escapePathDelimiters from '../shared/lib/router/utils/escape-path-delimiters'
import { getUtils } from './server-utils'
import isError, { getProperError } from '../lib/is-error'
import {
......@@ -144,6 +143,7 @@ import {
} from './web/spec-extension/adapters/next-request'
import { matchNextDataPathname } from './lib/match-next-data-pathname'
import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path'
import { decodePathParams } from './lib/router-utils/decode-path-params'
import { RSCPathnameNormalizer } from './normalizers/request/rsc'
import { PostponedPathnameNormalizer } from './normalizers/request/postponed'
import { stripFlightHeaders } from './app-render/strip-flight-headers'
......@@ -2359,25 +2359,7 @@ export default abstract class Server<
}
if (ssgCacheKey) {
// we only encode path delimiters for path segments from
// getStaticPaths so we need to attempt decoding the URL
// to match against and only escape the path delimiters
// this allows non-ascii values to be handled e.g. Japanese characters
// TODO: investigate adding this handling for non-SSG pages so
// non-ascii names work there also
ssgCacheKey = ssgCacheKey
.split('/')
.map((seg) => {
try {
seg = escapePathDelimiters(decodeURIComponent(seg), true)
} catch (_) {
// An improperly encoded URL was provided
throw new DecodeError('failed to decode param')
}
return seg
})
.join('/')
ssgCacheKey = decodePathParams(ssgCacheKey)
// ensure /index and / is normalized to one key
ssgCacheKey =
......@@ -2889,8 +2871,13 @@ export default abstract class Server<
//
// We use the `resolvedUrlPathname` for the development case when this
// is an app path since it doesn't include locale information.
let staticPathKey =
ssgCacheKey ?? (opts.dev && isAppPath ? resolvedUrlPathname : null)
//
// We decode the `resolvedUrlPathname` to correctly match the app path
// with prerendered paths.
let staticPathKey = ssgCacheKey
if (!staticPathKey && opts.dev && isAppPath) {
staticPathKey = decodePathParams(resolvedUrlPathname)
}
if (staticPathKey && query.amp) {
staticPathKey = staticPathKey.replace(/\.amp$/, '')
}
......
/* eslint-env jest */
import { decodePathParams } from './decode-path-params'
describe('decoding path params', () => {
it('should decode path params', () => {
const decodedPathParams = decodePathParams('sticks%20%26%20stones')
expect(decodedPathParams).toBe('sticks & stones')
})
it('should throw an error when the path param is improperly encoded', () => {
try {
// The segment %ZZ is an invalid percent-encoded sequence
// because %ZZ does not represent a valid hexadecimal character.
decodePathParams('sticks%ZZ%ZZ%ZZstones')
} catch (error) {
expect(error).toBeInstanceOf(Error)
expect((error as Error).message).toBe('Failed to decode path param(s).')
}
})
})
import escapePathDelimiters from '../../../shared/lib/router/utils/escape-path-delimiters'
import { DecodeError } from '../../../shared/lib/utils'
/**
* We only encode path delimiters for path segments from
* getStaticPaths so we need to attempt decoding the URL
* to match against and only escape the path delimiters
* this allows non-ascii values to be handled e.g.
* Japanese characters.
* */
function decodePathParams(pathname: string): string {
// TODO: investigate adding this handling for non-SSG
// pages so non-ascii names also work there.
return pathname
.split('/')
.map((seg) => {
try {
seg = escapePathDelimiters(decodeURIComponent(seg), true)
} catch (_) {
// An improperly encoded URL was provided
throw new DecodeError('Failed to decode path param(s).')
}
return seg
})
.join('/')
}
export { decodePathParams }
export const dynamicParams = false
export default async function Page({
params,
}: {
params: Promise<{ id: string }>
}) {
const id = (await params).id
return (
<main>
<div>params.id is {id}</div>
</main>
)
}
export function generateStaticParams() {
const id = 'sticks & stones'
return [{ id }]
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { nextTestSetup } from 'e2e-utils'
describe('prerender-encoding', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should respond with the prerendered page correctly', async () => {
const $ = await next.render$('/sticks%20%26%20stones')
expect($('div').text()).toBe('params.id is sticks%20%26%20stones')
})
})
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