Unverified Commit 5fc4325a authored by Javi Velasco's avatar Javi Velasco Committed by GitHub

Fix middleware i18n rewrites (#31174)

Fixes #30897

This PR fixes the linked issue where rewrites are not being applied for locale. It adds the corresponding test but also, as it was added in debugging process, it introduces a helper to read/write into the `request` object.

We are currently writing directly into the request by casting to `any` and then using flags like `_nextRewrote`. Instead, this PR puts all of this metadata under a symbol so it is not directly accessible. This also allows to have a single place where all of this metadata is listed so we can add comments describing the purpose of each flag.

In the same way, there is metadata written in the querystring. This is adding some types for it in order to throw some visibility on where is this metadata accessed. In an upcoming PR we can move all of it to the `request` object if possible to simplify the system.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`
parent 91a6e3af
......@@ -6,8 +6,9 @@ import { normalizeLocalePath } from '../../../../shared/lib/i18n/normalize-local
import pathMatch from '../../../../shared/lib/router/utils/path-match'
import { getRouteRegex } from '../../../../shared/lib/router/utils/route-regex'
import { getRouteMatcher } from '../../../../shared/lib/router/utils/route-matcher'
import prepareDestination, {
import {
matchHas,
prepareDestination,
} from '../../../../shared/lib/router/utils/prepare-destination'
import { __ApiPreviewProps } from '../../../../server/api-utils'
import { BuildManifest } from '../../../../server/get-page-files'
......@@ -23,6 +24,7 @@ import { denormalizePagePath } from '../../../../server/denormalize-page-path'
import cookie from 'next/dist/compiled/cookie'
import { TEMPORARY_REDIRECT_STATUS } from '../../../../shared/lib/constants'
import { NextConfig } from '../../../../server/config'
import { addRequestMeta } from '../../../../server/request-meta'
const getCustomRouteMatcher = pathMatch(true)
......@@ -99,12 +101,12 @@ export function getUtils({
}
if (params) {
const { parsedDestination } = prepareDestination(
rewrite.destination,
params,
parsedUrl.query,
true
)
const { parsedDestination } = prepareDestination({
appendParamsToQuery: true,
destination: rewrite.destination,
params: params,
query: parsedUrl.query,
})
Object.assign(parsedUrl.query, parsedDestination.query)
delete (parsedDestination as any).query
......@@ -372,7 +374,7 @@ export function getUtils({
if (detectedDomain) {
defaultLocale = detectedDomain.defaultLocale
detectedLocale = defaultLocale
;(req as any).__nextIsLocaleDomain = true
addRequestMeta(req, '__nextIsLocaleDomain', true)
}
// if not domain specific locale use accept-language preferred
......@@ -392,7 +394,7 @@ export function getUtils({
...parsedUrl,
pathname: localePathResult.pathname,
})
;(req as any).__nextStrippedLocale = true
addRequestMeta(req, '__nextStrippedLocale', true)
parsedUrl.pathname = localePathResult.pathname
}
......
import type { ComponentType } from 'react'
import type { FontManifest } from '../server/font-utils'
import type { GetStaticProps } from '../types'
import type { IncomingMessage, ServerResponse } from 'http'
import type { NextConfigComplete } from '../server/config-shared'
import type { NextParsedUrlQuery } from '../server/request-meta'
import url from 'url'
import { extname, join, dirname, sep } from 'path'
import { renderToHTML } from '../server/render'
......@@ -10,15 +16,10 @@ import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
import { normalizePagePath } from '../server/normalize-page-path'
import { SERVER_PROPS_EXPORT_ERROR } from '../lib/constants'
import '../server/node-polyfill-fetch'
import { IncomingMessage, ServerResponse } from 'http'
import { ComponentType } from 'react'
import { GetStaticProps } from '../types'
import { requireFontManifest } from '../server/require'
import { FontManifest } from '../server/font-utils'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { trace } from '../trace'
import { isInAmpMode } from '../shared/lib/amp'
import { NextConfigComplete } from '../server/config-shared'
import { setHttpAgentOptions } from '../server/config'
import RenderResult from '../server/render-result'
import isError from '../lib/is-error'
......@@ -39,7 +40,7 @@ interface AmpValidation {
interface PathMap {
page: string
query?: { [key: string]: string | string[] }
query?: NextParsedUrlQuery
}
interface ExportPageInput {
......@@ -128,7 +129,7 @@ export default async function exportPage({
let query = { ...originalQuery }
let params: { [key: string]: string | string[] } | undefined
let updatedPath = (query.__nextSsgPath as string) || path
let updatedPath = query.__nextSsgPath || path
let locale = query.__nextLocale || renderOpts.locale
delete query.__nextLocale
delete query.__nextSsgPath
......
This diff is collapsed.
......@@ -51,6 +51,7 @@ import { denormalizePagePath } from './denormalize-page-path'
import type { FontManifest } from './font-utils'
import type { LoadComponentsReturnType, ManifestItem } from './load-components'
import { normalizePagePath } from './normalize-page-path'
import { getRequestMeta, NextParsedUrlQuery } from './request-meta'
import {
allowedStatusCodes,
getRedirectStatus,
......@@ -277,7 +278,7 @@ export async function renderToHTML(
req: IncomingMessage,
res: ServerResponse,
pathname: string,
query: ParsedUrlQuery,
query: NextParsedUrlQuery,
renderOpts: RenderOpts
): Promise<RenderResult | null> {
// In dev we invalidate the cache by appending a timestamp to the resource URL.
......@@ -498,7 +499,7 @@ export async function renderToHTML(
renderOpts.defaultLocale,
renderOpts.domainLocales,
isPreview,
(req as any).__nextIsLocaleDomain
getRequestMeta(req, '__nextIsLocaleDomain')
)
const jsxStyleRegistry = createStyleRegistry()
const ctx = {
......@@ -1167,7 +1168,7 @@ export async function renderToHTML(
docComponentsRendered,
dangerousAsPath: router.asPath,
canonicalBase:
!renderOpts.ampPath && (req as any).__nextStrippedLocale
!renderOpts.ampPath && getRequestMeta(req, '__nextStrippedLocale')
? `${renderOpts.canonicalBase || ''}/${renderOpts.locale}`
: renderOpts.canonicalBase,
ampPath,
......
/* eslint-disable no-redeclare */
import type { ParsedUrlQuery } from 'querystring'
import type { IncomingMessage } from 'http'
import type { UrlWithParsedQuery } from 'url'
const NEXT_REQUEST_META = Symbol('NextRequestMeta')
interface NextIncomingMessage extends IncomingMessage {
[NEXT_REQUEST_META]?: RequestMeta
}
interface RequestMeta {
__NEXT_INIT_QUERY?: ParsedUrlQuery
__NEXT_INIT_URL?: string
__nextHadTrailingSlash?: boolean
__nextIsLocaleDomain?: boolean
__nextStrippedLocale?: boolean
_nextDidRewrite?: boolean
_nextHadBasePath?: boolean
_nextRewroteUrl?: string
}
export function getRequestMeta(
req: NextIncomingMessage,
key?: undefined
): RequestMeta
export function getRequestMeta<K extends keyof RequestMeta>(
req: NextIncomingMessage,
key: K
): RequestMeta[K]
export function getRequestMeta<K extends keyof RequestMeta>(
req: NextIncomingMessage,
key?: K
): RequestMeta | RequestMeta[K] {
const meta = req[NEXT_REQUEST_META] || {}
return typeof key === 'string' ? meta[key] : meta
}
export function setRequestMeta(req: NextIncomingMessage, meta: RequestMeta) {
req[NEXT_REQUEST_META] = meta
return getRequestMeta(req)
}
export function addRequestMeta<K extends keyof RequestMeta>(
request: NextIncomingMessage,
key: K,
value: RequestMeta[K]
) {
const meta = getRequestMeta(request)
meta[key] = value
return setRequestMeta(request, meta)
}
export type NextParsedUrlQuery = ParsedUrlQuery & {
__nextDefaultLocale?: string
__nextFallback?: 'true'
__nextLocale?: string
__nextSsgPath?: string
_nextBubbleNoFallback?: '1'
_nextDataReq?: '1'
amp?: '1'
}
export interface NextUrlWithParsedQuery extends UrlWithParsedQuery {
query: NextParsedUrlQuery
}
import type { IncomingMessage, ServerResponse } from 'http'
import type { ParsedUrlQuery } from 'querystring'
import type { UrlWithParsedQuery } from 'url'
import type { NextUrlWithParsedQuery } from './request-meta'
import pathMatch from '../shared/lib/router/utils/path-match'
import { removePathTrailingSlash } from '../client/normalize-trailing-slash'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { RouteHas } from '../lib/load-custom-routes'
import { matchHas } from '../shared/lib/router/utils/prepare-destination'
import { getRequestMeta } from './request-meta'
export const route = pathMatch()
......@@ -33,7 +34,7 @@ export type Route = {
req: IncomingMessage,
res: ServerResponse,
params: Params,
parsedUrl: UrlWithParsedQuery
parsedUrl: NextUrlWithParsedQuery
) => Promise<RouteResult> | RouteResult
}
......@@ -122,7 +123,7 @@ export default class Router {
async execute(
req: IncomingMessage,
res: ServerResponse,
parsedUrl: UrlWithParsedQuery
parsedUrl: NextUrlWithParsedQuery
): Promise<boolean> {
// memoize page check calls so we don't duplicate checks for pages
const pageChecks: { [name: string]: Promise<boolean> } = {}
......@@ -139,7 +140,7 @@ export default class Router {
let parsedUrlUpdated = parsedUrl
const applyCheckTrue = async (checkParsedUrl: UrlWithParsedQuery) => {
const applyCheckTrue = async (checkParsedUrl: NextUrlWithParsedQuery) => {
const originalFsPathname = checkParsedUrl.pathname
const fsPathname = replaceBasePath(this.basePath, originalFsPathname!)
......@@ -264,7 +265,7 @@ export default class Router {
...(this.useFileSystemPublicRoutes ? [this.catchAllRoute] : []),
]
const originallyHadBasePath =
!this.basePath || (req as any)._nextHadBasePath
!this.basePath || getRequestMeta(req, '_nextHadBasePath')
for (const testRoute of allRoutes) {
// if basePath is being used, the basePath will still be included
......@@ -308,14 +309,14 @@ export default class Router {
}
if (
(req as any).__nextHadTrailingSlash &&
getRequestMeta(req, '__nextHadTrailingSlash') &&
!currentPathname.endsWith('/')
) {
currentPathname += '/'
}
} else {
currentPathname = `${
(req as any)._nextHadBasePath ? activeBasePath : ''
getRequestMeta(req, '_nextHadBasePath') ? activeBasePath : ''
}${
activeBasePath && localePathResult.pathname === '/'
? ''
......@@ -340,7 +341,10 @@ export default class Router {
// since we require basePath be present for non-custom-routes we
// 404 here when we matched an fs route
if (!keepBasePath) {
if (!originallyHadBasePath && !(req as any)._nextDidRewrite) {
if (
!originallyHadBasePath &&
!getRequestMeta(req, '_nextDidRewrite')
) {
if (requireBasePath) {
// consider this a non-match so the 404 renders
return false
......@@ -360,8 +364,8 @@ export default class Router {
return true
}
// since the fs route didn't match we need to re-add the basePath
// to continue checking rewrites with the basePath present
// since the fs route didn't finish routing we need to re-add the
// basePath to continue checking with the basePath present
if (!keepBasePath) {
parsedUrlUpdated.pathname = originalPathname
}
......
import type { IncomingMessage } from 'http'
import type { ParsedUrlQuery } from 'querystring'
import { parseUrl } from './parse-url'
import * as pathToRegexp from 'next/dist/compiled/path-to-regexp'
import type { Key } from 'next/dist/compiled/path-to-regexp'
import type { NextParsedUrlQuery } from '../../../../server/request-meta'
import type { Params } from '../../../../server/router'
import type { RouteHas } from '../../../../lib/load-custom-routes'
type Params = { [param: string]: any }
// ensure only a-zA-Z are used for param names for proper interpolating
// with path-to-regexp
export const getSafeParamName = (paramName: string) => {
let newParamName = ''
for (let i = 0; i < paramName.length; i++) {
const charCode = paramName.charCodeAt(i)
if (
(charCode > 64 && charCode < 91) || // A-Z
(charCode > 96 && charCode < 123) // a-z
) {
newParamName += paramName[i]
}
}
return newParamName
}
import { compile, pathToRegexp } from 'next/dist/compiled/path-to-regexp'
import { parseUrl } from './parse-url'
export function matchHas(
req: IncomingMessage,
......@@ -124,31 +106,23 @@ export function compileNonPath(value: string, params: Params): string {
// the value needs to start with a forward-slash to be compiled
// correctly
return pathToRegexp
.compile(`/${value}`, { validate: false })(params)
.substr(1)
return compile(`/${value}`, { validate: false })(params).substr(1)
}
const escapeSegment = (str: string, segmentName: string) =>
str.replace(new RegExp(`:${segmentName}`, 'g'), `__ESC_COLON_${segmentName}`)
const unescapeSegments = (str: string) => str.replace(/__ESC_COLON_/gi, ':')
export default function prepareDestination(
destination: string,
params: Params,
query: ParsedUrlQuery,
export function prepareDestination(args: {
appendParamsToQuery: boolean
) {
// clone query so we don't modify the original
query = Object.assign({}, query)
destination: string
params: Params
query: NextParsedUrlQuery
}) {
const query = Object.assign({}, args.query)
const hadLocale = query.__nextLocale
delete query.__nextLocale
delete query.__nextDefaultLocale
let escapedDestination = destination
let escapedDestination = args.destination
for (const param of Object.keys({ ...params, ...query })) {
for (const param of Object.keys({ ...args.params, ...query })) {
escapedDestination = escapeSegment(escapedDestination, param)
}
......@@ -158,17 +132,17 @@ export default function prepareDestination(
`${parsedDestination.pathname!}${parsedDestination.hash || ''}`
)
const destHostname = unescapeSegments(parsedDestination.hostname || '')
const destPathParamKeys: pathToRegexp.Key[] = []
const destHostnameParamKeys: pathToRegexp.Key[] = []
pathToRegexp.pathToRegexp(destPath, destPathParamKeys)
pathToRegexp.pathToRegexp(destHostname, destHostnameParamKeys)
const destPathParamKeys: Key[] = []
const destHostnameParamKeys: Key[] = []
pathToRegexp(destPath, destPathParamKeys)
pathToRegexp(destHostname, destHostnameParamKeys)
const destParams: (string | number)[] = []
destPathParamKeys.forEach((key) => destParams.push(key.name))
destHostnameParamKeys.forEach((key) => destParams.push(key.name))
const destPathCompiler = pathToRegexp.compile(
const destPathCompiler = compile(
destPath,
// we don't validate while compiling the destination since we should
// have already validated before we got to this point and validating
......@@ -178,10 +152,8 @@ export default function prepareDestination(
// params from a separate path-regex into another
{ validate: false }
)
const destHostnameCompiler = pathToRegexp.compile(destHostname, {
validate: false,
})
let newUrl
const destHostnameCompiler = compile(destHostname, { validate: false })
// update any params in query values
for (const [key, strOrArray] of Object.entries(destQuery)) {
......@@ -189,16 +161,16 @@ export default function prepareDestination(
// correctly
if (Array.isArray(strOrArray)) {
destQuery[key] = strOrArray.map((value) =>
compileNonPath(unescapeSegments(value), params)
compileNonPath(unescapeSegments(value), args.params)
)
} else {
destQuery[key] = compileNonPath(unescapeSegments(strOrArray), params)
destQuery[key] = compileNonPath(unescapeSegments(strOrArray), args.params)
}
}
// add path params to query if it's not a redirect and not
// already defined in destination query or path
let paramKeys = Object.keys(params)
let paramKeys = Object.keys(args.params)
// remove internal param for i18n
if (hadLocale) {
......@@ -206,30 +178,28 @@ export default function prepareDestination(
}
if (
appendParamsToQuery &&
args.appendParamsToQuery &&
!paramKeys.some((key) => destParams.includes(key))
) {
for (const key of paramKeys) {
if (!(key in destQuery)) {
destQuery[key] = params[key]
destQuery[key] = args.params[key]
}
}
}
let newUrl
try {
newUrl = destPathCompiler(params)
newUrl = destPathCompiler(args.params)
const [pathname, hash] = newUrl.split('#')
parsedDestination.hostname = destHostnameCompiler(params)
parsedDestination.hostname = destHostnameCompiler(args.params)
parsedDestination.pathname = pathname
parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}`
delete (parsedDestination as any).search
} catch (err) {
if (
(err as Error).message.match(
/Expected .*? to not repeat, but got an array/
)
) {
} catch (err: any) {
if (err.message.match(/Expected .*? to not repeat, but got an array/)) {
throw new Error(
`To use a multi-match in the destination you must add \`*\` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match`
)
......@@ -251,3 +221,34 @@ export default function prepareDestination(
parsedDestination,
}
}
/**
* Ensure only a-zA-Z are used for param names for proper interpolating
* with path-to-regexp
*/
function getSafeParamName(paramName: string) {
let newParamName = ''
for (let i = 0; i < paramName.length; i++) {
const charCode = paramName.charCodeAt(i)
if (
(charCode > 64 && charCode < 91) || // A-Z
(charCode > 96 && charCode < 123) // a-z
) {
newParamName += paramName[i]
}
}
return newParamName
}
function escapeSegment(str: string, segmentName: string) {
return str.replace(
new RegExp(`:${segmentName}`, 'g'),
`__ESC_COLON_${segmentName}`
)
}
function unescapeSegments(str: string) {
return str.replace(/__ESC_COLON_/gi, ':')
}
import { ParsedUrlQuery } from 'querystring'
import pathMatch from './path-match'
import prepareDestination, { matchHas } from './prepare-destination'
import { matchHas, prepareDestination } from './prepare-destination'
import { Rewrite } from '../../../../lib/load-custom-routes'
import { removePathTrailingSlash } from '../../../../client/normalize-trailing-slash'
import { normalizeLocalePath } from '../../i18n/normalize-locale-path'
......@@ -67,12 +67,12 @@ export default function resolveRewrites(
// this is a proxied rewrite which isn't handled on the client
return true
}
const destRes = prepareDestination(
rewrite.destination,
params,
query,
true
)
const destRes = prepareDestination({
appendParamsToQuery: true,
destination: rewrite.destination,
params: params,
query: query,
})
parsedAs = destRes.parsedDestination
asPath = destRes.newUrl
Object.assign(query, destRes.parsedDestination.query)
......
module.exports = {
i18n: {
locales: ['default', 'en', 'es', 'fr', 'zh'],
defaultLocale: 'default',
},
}
import { NextResponse } from 'next/server'
const PUBLIC_FILE = /\.(.*)$/
export function middleware(req) {
const locale = req.nextUrl.searchParams.get('my-locale')
const country = req.nextUrl.searchParams.get('country') || 'us'
if (locale) {
req.nextUrl.locale = locale
}
if (
!PUBLIC_FILE.test(req.nextUrl.pathname) &&
!req.nextUrl.pathname.includes('/api/')
) {
req.nextUrl.pathname = `/test/${country}`
return NextResponse.rewrite(req.nextUrl)
}
}
export const getStaticPaths = async () => {
return {
fallback: 'blocking',
paths: [],
}
}
export const getStaticProps = async ({ params: { country }, locale }) => {
return {
props: { country, locale },
revalidate: false,
}
}
export default function CountryPage({ locale, country }) {
return (
<ul>
<li id="country">{country}</li>
<li id="locale">{locale}</li>
</ul>
)
}
/* eslint-env jest */
import { join } from 'path'
import cheerio from 'cheerio'
import {
fetchViaHTTP,
findPort,
killApp,
launchApp,
nextBuild,
nextStart,
} from 'next-test-utils'
const context = {}
context.appDir = join(__dirname, '../')
jest.setTimeout(1000 * 60 * 2)
describe('Middleware i18n tests', () => {
describe('dev mode', () => {
beforeAll(async () => {
context.appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort)
})
afterAll(() => killApp(context.app))
runTests()
})
describe('production mode', () => {
beforeAll(async () => {
await nextBuild(context.appDir, undefined, {
stderr: true,
stdout: true,
})
context.appPort = await findPort()
context.app = await nextStart(context.appDir, context.appPort)
})
afterAll(() => killApp(context.app))
runTests()
})
})
function runTests() {
it(`reads the locale from the pathname`, async () => {
const res = await fetchViaHTTP(context.appPort, '/fr', { country: 'spain' })
const html = await res.text()
const $ = cheerio.load(html)
expect($('#locale').text()).toBe('fr')
expect($('#country').text()).toBe('spain')
})
it(`rewrites from a locale correctly`, async () => {
const res = await fetchViaHTTP(context.appPort, '/', { 'my-locale': 'es' })
const html = await res.text()
const $ = cheerio.load(html)
expect($('#locale').text()).toBe('es')
expect($('#country').text()).toBe('us')
})
}
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