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 ...@@ -6,8 +6,9 @@ import { normalizeLocalePath } from '../../../../shared/lib/i18n/normalize-local
import pathMatch from '../../../../shared/lib/router/utils/path-match' import pathMatch from '../../../../shared/lib/router/utils/path-match'
import { getRouteRegex } from '../../../../shared/lib/router/utils/route-regex' import { getRouteRegex } from '../../../../shared/lib/router/utils/route-regex'
import { getRouteMatcher } from '../../../../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../../../../shared/lib/router/utils/route-matcher'
import prepareDestination, { import {
matchHas, matchHas,
prepareDestination,
} from '../../../../shared/lib/router/utils/prepare-destination' } from '../../../../shared/lib/router/utils/prepare-destination'
import { __ApiPreviewProps } from '../../../../server/api-utils' import { __ApiPreviewProps } from '../../../../server/api-utils'
import { BuildManifest } from '../../../../server/get-page-files' import { BuildManifest } from '../../../../server/get-page-files'
...@@ -23,6 +24,7 @@ import { denormalizePagePath } from '../../../../server/denormalize-page-path' ...@@ -23,6 +24,7 @@ import { denormalizePagePath } from '../../../../server/denormalize-page-path'
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 { NextConfig } from '../../../../server/config' import { NextConfig } from '../../../../server/config'
import { addRequestMeta } from '../../../../server/request-meta'
const getCustomRouteMatcher = pathMatch(true) const getCustomRouteMatcher = pathMatch(true)
...@@ -99,12 +101,12 @@ export function getUtils({ ...@@ -99,12 +101,12 @@ export function getUtils({
} }
if (params) { if (params) {
const { parsedDestination } = prepareDestination( const { parsedDestination } = prepareDestination({
rewrite.destination, appendParamsToQuery: true,
params, destination: rewrite.destination,
parsedUrl.query, params: params,
true query: parsedUrl.query,
) })
Object.assign(parsedUrl.query, parsedDestination.query) Object.assign(parsedUrl.query, parsedDestination.query)
delete (parsedDestination as any).query delete (parsedDestination as any).query
...@@ -372,7 +374,7 @@ export function getUtils({ ...@@ -372,7 +374,7 @@ export function getUtils({
if (detectedDomain) { if (detectedDomain) {
defaultLocale = detectedDomain.defaultLocale defaultLocale = detectedDomain.defaultLocale
detectedLocale = defaultLocale detectedLocale = defaultLocale
;(req as any).__nextIsLocaleDomain = true addRequestMeta(req, '__nextIsLocaleDomain', true)
} }
// if not domain specific locale use accept-language preferred // if not domain specific locale use accept-language preferred
...@@ -392,7 +394,7 @@ export function getUtils({ ...@@ -392,7 +394,7 @@ export function getUtils({
...parsedUrl, ...parsedUrl,
pathname: localePathResult.pathname, pathname: localePathResult.pathname,
}) })
;(req as any).__nextStrippedLocale = true addRequestMeta(req, '__nextStrippedLocale', true)
parsedUrl.pathname = localePathResult.pathname 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 url from 'url'
import { extname, join, dirname, sep } from 'path' import { extname, join, dirname, sep } from 'path'
import { renderToHTML } from '../server/render' import { renderToHTML } from '../server/render'
...@@ -10,15 +16,10 @@ import { getRouteRegex } from '../shared/lib/router/utils/route-regex' ...@@ -10,15 +16,10 @@ import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
import { normalizePagePath } from '../server/normalize-page-path' import { normalizePagePath } from '../server/normalize-page-path'
import { SERVER_PROPS_EXPORT_ERROR } from '../lib/constants' import { SERVER_PROPS_EXPORT_ERROR } from '../lib/constants'
import '../server/node-polyfill-fetch' import '../server/node-polyfill-fetch'
import { IncomingMessage, ServerResponse } from 'http'
import { ComponentType } from 'react'
import { GetStaticProps } from '../types'
import { requireFontManifest } from '../server/require' import { requireFontManifest } from '../server/require'
import { FontManifest } from '../server/font-utils'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { trace } from '../trace' import { trace } from '../trace'
import { isInAmpMode } from '../shared/lib/amp' import { isInAmpMode } from '../shared/lib/amp'
import { NextConfigComplete } from '../server/config-shared'
import { setHttpAgentOptions } from '../server/config' import { setHttpAgentOptions } from '../server/config'
import RenderResult from '../server/render-result' import RenderResult from '../server/render-result'
import isError from '../lib/is-error' import isError from '../lib/is-error'
...@@ -39,7 +40,7 @@ interface AmpValidation { ...@@ -39,7 +40,7 @@ interface AmpValidation {
interface PathMap { interface PathMap {
page: string page: string
query?: { [key: string]: string | string[] } query?: NextParsedUrlQuery
} }
interface ExportPageInput { interface ExportPageInput {
...@@ -128,7 +129,7 @@ export default async function exportPage({ ...@@ -128,7 +129,7 @@ export default async function exportPage({
let query = { ...originalQuery } let query = { ...originalQuery }
let params: { [key: string]: string | string[] } | undefined 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 let locale = query.__nextLocale || renderOpts.locale
delete query.__nextLocale delete query.__nextLocale
delete query.__nextSsgPath delete query.__nextSsgPath
......
This diff is collapsed.
...@@ -51,6 +51,7 @@ import { denormalizePagePath } from './denormalize-page-path' ...@@ -51,6 +51,7 @@ import { denormalizePagePath } from './denormalize-page-path'
import type { FontManifest } from './font-utils' import type { FontManifest } from './font-utils'
import type { LoadComponentsReturnType, ManifestItem } from './load-components' import type { LoadComponentsReturnType, ManifestItem } from './load-components'
import { normalizePagePath } from './normalize-page-path' import { normalizePagePath } from './normalize-page-path'
import { getRequestMeta, NextParsedUrlQuery } from './request-meta'
import { import {
allowedStatusCodes, allowedStatusCodes,
getRedirectStatus, getRedirectStatus,
...@@ -277,7 +278,7 @@ export async function renderToHTML( ...@@ -277,7 +278,7 @@ export async function renderToHTML(
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
pathname: string, pathname: string,
query: ParsedUrlQuery, query: NextParsedUrlQuery,
renderOpts: RenderOpts renderOpts: RenderOpts
): Promise<RenderResult | null> { ): Promise<RenderResult | null> {
// In dev we invalidate the cache by appending a timestamp to the resource URL. // In dev we invalidate the cache by appending a timestamp to the resource URL.
...@@ -498,7 +499,7 @@ export async function renderToHTML( ...@@ -498,7 +499,7 @@ export async function renderToHTML(
renderOpts.defaultLocale, renderOpts.defaultLocale,
renderOpts.domainLocales, renderOpts.domainLocales,
isPreview, isPreview,
(req as any).__nextIsLocaleDomain getRequestMeta(req, '__nextIsLocaleDomain')
) )
const jsxStyleRegistry = createStyleRegistry() const jsxStyleRegistry = createStyleRegistry()
const ctx = { const ctx = {
...@@ -1167,7 +1168,7 @@ export async function renderToHTML( ...@@ -1167,7 +1168,7 @@ export async function renderToHTML(
docComponentsRendered, docComponentsRendered,
dangerousAsPath: router.asPath, dangerousAsPath: router.asPath,
canonicalBase: canonicalBase:
!renderOpts.ampPath && (req as any).__nextStrippedLocale !renderOpts.ampPath && getRequestMeta(req, '__nextStrippedLocale')
? `${renderOpts.canonicalBase || ''}/${renderOpts.locale}` ? `${renderOpts.canonicalBase || ''}/${renderOpts.locale}`
: renderOpts.canonicalBase, : renderOpts.canonicalBase,
ampPath, 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 { IncomingMessage, ServerResponse } from 'http'
import type { ParsedUrlQuery } from 'querystring' 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 pathMatch from '../shared/lib/router/utils/path-match'
import { removePathTrailingSlash } from '../client/normalize-trailing-slash' import { removePathTrailingSlash } from '../client/normalize-trailing-slash'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { RouteHas } from '../lib/load-custom-routes' import { RouteHas } from '../lib/load-custom-routes'
import { matchHas } from '../shared/lib/router/utils/prepare-destination' import { matchHas } from '../shared/lib/router/utils/prepare-destination'
import { getRequestMeta } from './request-meta'
export const route = pathMatch() export const route = pathMatch()
...@@ -33,7 +34,7 @@ export type Route = { ...@@ -33,7 +34,7 @@ export type Route = {
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
params: Params, params: Params,
parsedUrl: UrlWithParsedQuery parsedUrl: NextUrlWithParsedQuery
) => Promise<RouteResult> | RouteResult ) => Promise<RouteResult> | RouteResult
} }
...@@ -122,7 +123,7 @@ export default class Router { ...@@ -122,7 +123,7 @@ export default class Router {
async execute( async execute(
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
parsedUrl: UrlWithParsedQuery parsedUrl: NextUrlWithParsedQuery
): Promise<boolean> { ): Promise<boolean> {
// memoize page check calls so we don't duplicate checks for pages // memoize page check calls so we don't duplicate checks for pages
const pageChecks: { [name: string]: Promise<boolean> } = {} const pageChecks: { [name: string]: Promise<boolean> } = {}
...@@ -139,7 +140,7 @@ export default class Router { ...@@ -139,7 +140,7 @@ export default class Router {
let parsedUrlUpdated = parsedUrl let parsedUrlUpdated = parsedUrl
const applyCheckTrue = async (checkParsedUrl: UrlWithParsedQuery) => { const applyCheckTrue = async (checkParsedUrl: NextUrlWithParsedQuery) => {
const originalFsPathname = checkParsedUrl.pathname const originalFsPathname = checkParsedUrl.pathname
const fsPathname = replaceBasePath(this.basePath, originalFsPathname!) const fsPathname = replaceBasePath(this.basePath, originalFsPathname!)
...@@ -264,7 +265,7 @@ export default class Router { ...@@ -264,7 +265,7 @@ export default class Router {
...(this.useFileSystemPublicRoutes ? [this.catchAllRoute] : []), ...(this.useFileSystemPublicRoutes ? [this.catchAllRoute] : []),
] ]
const originallyHadBasePath = const originallyHadBasePath =
!this.basePath || (req as any)._nextHadBasePath !this.basePath || getRequestMeta(req, '_nextHadBasePath')
for (const testRoute of allRoutes) { for (const testRoute of allRoutes) {
// if basePath is being used, the basePath will still be included // if basePath is being used, the basePath will still be included
...@@ -308,14 +309,14 @@ export default class Router { ...@@ -308,14 +309,14 @@ export default class Router {
} }
if ( if (
(req as any).__nextHadTrailingSlash && getRequestMeta(req, '__nextHadTrailingSlash') &&
!currentPathname.endsWith('/') !currentPathname.endsWith('/')
) { ) {
currentPathname += '/' currentPathname += '/'
} }
} else { } else {
currentPathname = `${ currentPathname = `${
(req as any)._nextHadBasePath ? activeBasePath : '' getRequestMeta(req, '_nextHadBasePath') ? activeBasePath : ''
}${ }${
activeBasePath && localePathResult.pathname === '/' activeBasePath && localePathResult.pathname === '/'
? '' ? ''
...@@ -340,7 +341,10 @@ export default class Router { ...@@ -340,7 +341,10 @@ export default class Router {
// since we require basePath be present for non-custom-routes we // since we require basePath be present for non-custom-routes we
// 404 here when we matched an fs route // 404 here when we matched an fs route
if (!keepBasePath) { if (!keepBasePath) {
if (!originallyHadBasePath && !(req as any)._nextDidRewrite) { if (
!originallyHadBasePath &&
!getRequestMeta(req, '_nextDidRewrite')
) {
if (requireBasePath) { if (requireBasePath) {
// consider this a non-match so the 404 renders // consider this a non-match so the 404 renders
return false return false
...@@ -360,8 +364,8 @@ export default class Router { ...@@ -360,8 +364,8 @@ export default class Router {
return true return true
} }
// since the fs route didn't match we need to re-add the basePath // since the fs route didn't finish routing we need to re-add the
// to continue checking rewrites with the basePath present // basePath to continue checking with the basePath present
if (!keepBasePath) { if (!keepBasePath) {
parsedUrlUpdated.pathname = originalPathname parsedUrlUpdated.pathname = originalPathname
} }
......
import type { IncomingMessage } from 'http' import type { IncomingMessage } from 'http'
import type { ParsedUrlQuery } from 'querystring' import type { Key } from 'next/dist/compiled/path-to-regexp'
import { parseUrl } from './parse-url' import type { NextParsedUrlQuery } from '../../../../server/request-meta'
import * as pathToRegexp from 'next/dist/compiled/path-to-regexp' import type { Params } from '../../../../server/router'
import type { RouteHas } from '../../../../lib/load-custom-routes' import type { RouteHas } from '../../../../lib/load-custom-routes'
import { compile, pathToRegexp } from 'next/dist/compiled/path-to-regexp'
type Params = { [param: string]: any } import { parseUrl } from './parse-url'
// 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
}
export function matchHas( export function matchHas(
req: IncomingMessage, req: IncomingMessage,
...@@ -124,31 +106,23 @@ export function compileNonPath(value: string, params: Params): string { ...@@ -124,31 +106,23 @@ export function compileNonPath(value: string, params: Params): string {
// the value needs to start with a forward-slash to be compiled // the value needs to start with a forward-slash to be compiled
// correctly // correctly
return pathToRegexp return compile(`/${value}`, { validate: false })(params).substr(1)
.compile(`/${value}`, { validate: false })(params)
.substr(1)
} }
const escapeSegment = (str: string, segmentName: string) => export function prepareDestination(args: {
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,
appendParamsToQuery: boolean appendParamsToQuery: boolean
) { destination: string
// clone query so we don't modify the original params: Params
query = Object.assign({}, query) query: NextParsedUrlQuery
}) {
const query = Object.assign({}, args.query)
const hadLocale = query.__nextLocale const hadLocale = query.__nextLocale
delete query.__nextLocale delete query.__nextLocale
delete query.__nextDefaultLocale 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) escapedDestination = escapeSegment(escapedDestination, param)
} }
...@@ -158,17 +132,17 @@ export default function prepareDestination( ...@@ -158,17 +132,17 @@ export default function prepareDestination(
`${parsedDestination.pathname!}${parsedDestination.hash || ''}` `${parsedDestination.pathname!}${parsedDestination.hash || ''}`
) )
const destHostname = unescapeSegments(parsedDestination.hostname || '') const destHostname = unescapeSegments(parsedDestination.hostname || '')
const destPathParamKeys: pathToRegexp.Key[] = [] const destPathParamKeys: Key[] = []
const destHostnameParamKeys: pathToRegexp.Key[] = [] const destHostnameParamKeys: Key[] = []
pathToRegexp.pathToRegexp(destPath, destPathParamKeys) pathToRegexp(destPath, destPathParamKeys)
pathToRegexp.pathToRegexp(destHostname, destHostnameParamKeys) pathToRegexp(destHostname, destHostnameParamKeys)
const destParams: (string | number)[] = [] const destParams: (string | number)[] = []
destPathParamKeys.forEach((key) => destParams.push(key.name)) destPathParamKeys.forEach((key) => destParams.push(key.name))
destHostnameParamKeys.forEach((key) => destParams.push(key.name)) destHostnameParamKeys.forEach((key) => destParams.push(key.name))
const destPathCompiler = pathToRegexp.compile( const destPathCompiler = compile(
destPath, destPath,
// we don't validate while compiling the destination since we should // we don't validate while compiling the destination since we should
// have already validated before we got to this point and validating // have already validated before we got to this point and validating
...@@ -178,10 +152,8 @@ export default function prepareDestination( ...@@ -178,10 +152,8 @@ export default function prepareDestination(
// params from a separate path-regex into another // params from a separate path-regex into another
{ validate: false } { validate: false }
) )
const destHostnameCompiler = pathToRegexp.compile(destHostname, {
validate: false, const destHostnameCompiler = compile(destHostname, { validate: false })
})
let newUrl
// update any params in query values // update any params in query values
for (const [key, strOrArray] of Object.entries(destQuery)) { for (const [key, strOrArray] of Object.entries(destQuery)) {
...@@ -189,16 +161,16 @@ export default function prepareDestination( ...@@ -189,16 +161,16 @@ export default function prepareDestination(
// correctly // correctly
if (Array.isArray(strOrArray)) { if (Array.isArray(strOrArray)) {
destQuery[key] = strOrArray.map((value) => destQuery[key] = strOrArray.map((value) =>
compileNonPath(unescapeSegments(value), params) compileNonPath(unescapeSegments(value), args.params)
) )
} else { } 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 // add path params to query if it's not a redirect and not
// already defined in destination query or path // already defined in destination query or path
let paramKeys = Object.keys(params) let paramKeys = Object.keys(args.params)
// remove internal param for i18n // remove internal param for i18n
if (hadLocale) { if (hadLocale) {
...@@ -206,30 +178,28 @@ export default function prepareDestination( ...@@ -206,30 +178,28 @@ export default function prepareDestination(
} }
if ( if (
appendParamsToQuery && args.appendParamsToQuery &&
!paramKeys.some((key) => destParams.includes(key)) !paramKeys.some((key) => destParams.includes(key))
) { ) {
for (const key of paramKeys) { for (const key of paramKeys) {
if (!(key in destQuery)) { if (!(key in destQuery)) {
destQuery[key] = params[key] destQuery[key] = args.params[key]
} }
} }
} }
let newUrl
try { try {
newUrl = destPathCompiler(params) newUrl = destPathCompiler(args.params)
const [pathname, hash] = newUrl.split('#') const [pathname, hash] = newUrl.split('#')
parsedDestination.hostname = destHostnameCompiler(params) parsedDestination.hostname = destHostnameCompiler(args.params)
parsedDestination.pathname = pathname parsedDestination.pathname = pathname
parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}` parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}`
delete (parsedDestination as any).search delete (parsedDestination as any).search
} catch (err) { } catch (err: any) {
if ( if (err.message.match(/Expected .*? to not repeat, but got an array/)) {
(err as Error).message.match(
/Expected .*? to not repeat, but got an array/
)
) {
throw new Error( 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` `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( ...@@ -251,3 +221,34 @@ export default function prepareDestination(
parsedDestination, 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 { ParsedUrlQuery } from 'querystring'
import pathMatch from './path-match' 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 { Rewrite } from '../../../../lib/load-custom-routes'
import { removePathTrailingSlash } from '../../../../client/normalize-trailing-slash' import { removePathTrailingSlash } from '../../../../client/normalize-trailing-slash'
import { normalizeLocalePath } from '../../i18n/normalize-locale-path' import { normalizeLocalePath } from '../../i18n/normalize-locale-path'
...@@ -67,12 +67,12 @@ export default function resolveRewrites( ...@@ -67,12 +67,12 @@ export default function resolveRewrites(
// this is a proxied rewrite which isn't handled on the client // this is a proxied rewrite which isn't handled on the client
return true return true
} }
const destRes = prepareDestination( const destRes = prepareDestination({
rewrite.destination, appendParamsToQuery: true,
params, destination: rewrite.destination,
query, params: params,
true query: query,
) })
parsedAs = destRes.parsedDestination parsedAs = destRes.parsedDestination
asPath = destRes.newUrl asPath = destRes.newUrl
Object.assign(query, destRes.parsedDestination.query) 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