rsnext/packages/next/shared/lib/i18n/normalize-locale-path.ts
Steven eb0bd63af4
Fix basePath replacing server-side and normalizeLocalePath() when path is empty string (#30978)
This fixes our `basePath` detection/replacing server-side as we were incorrectly considering `/docss` a match for a `basePath` of `/docs` which caused us to have an unexpected value in the `normalizeLocalePath` function. 

- Fixes #22429
- Regression introduced in #17757 
- Fixes: https://github.com/vercel/next.js/issues/31423

Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
2021-11-15 17:33:21 +00:00

40 lines
1,004 B
TypeScript

export interface PathLocale {
detectedLocale?: string
pathname: string
}
/**
* For a pathname that may include a locale from a list of locales, it
* removes the locale from the pathname returning it alongside with the
* detected locale.
*
* @param pathname A pathname that may include a locale.
* @param locales A list of locales.
* @returns The detected locale and pathname without locale
*/
export function normalizeLocalePath(
pathname: string,
locales?: string[]
): PathLocale {
let detectedLocale: string | undefined
// first item will be empty string from splitting at first char
const pathnameParts = pathname.split('/')
;(locales || []).some((locale) => {
if (
pathnameParts[1] &&
pathnameParts[1].toLowerCase() === locale.toLowerCase()
) {
detectedLocale = locale
pathnameParts.splice(1, 1)
pathname = pathnameParts.join('/') || '/'
return true
}
return false
})
return {
pathname,
detectedLocale,
}
}