Skip to content

Commit

Permalink
fix: middleware i18n normalization
Browse files Browse the repository at this point in the history
  • Loading branch information
orinokai committed Jun 13, 2024
1 parent 1d6e0c5 commit 2326319
Showing 1 changed file with 15 additions and 24 deletions.
39 changes: 15 additions & 24 deletions edge-runtime/lib/next-request.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import type { Context } from '@netlify/edge-functions'

import { addBasePath, normalizeDataUrl, normalizeLocalePath, removeBasePath } from './util.ts'
import {
addBasePath,
addTrailingSlash,
normalizeDataUrl,
normalizeLocalePath,
removeBasePath,
} from './util.ts'

interface I18NConfig {
defaultLocale: string
Expand Down Expand Up @@ -40,44 +46,29 @@ const normalizeRequestURL = (
nextConfig?: RequestData['nextConfig'],
): { url: string; detectedLocale?: string } => {
const url = new URL(originalURL)

url.pathname = removeBasePath(url.pathname, nextConfig?.basePath)
const didRemoveBasePath = url.toString() !== originalURL

let detectedLocale: string | undefined

let pathname = removeBasePath(url.pathname, nextConfig?.basePath)

// If the i18n config is present, remove the locale from the URL and store it
if (nextConfig?.i18n) {
const { pathname, detectedLocale: detected } = normalizeLocalePath(
url.pathname,
nextConfig?.i18n?.locales,
)
if (!nextConfig?.skipMiddlewareUrlNormalize) {
url.pathname = pathname || '/'
}
detectedLocale = detected
;({ detectedLocale } = normalizeLocalePath(pathname, nextConfig?.i18n?.locales))
}

if (!nextConfig?.skipMiddlewareUrlNormalize) {
// We want to run middleware for data requests and expose the URL of the
// corresponding pages, so we have to normalize the URLs before running
// the handler.
url.pathname = normalizeDataUrl(url.pathname)
pathname = normalizeDataUrl(pathname)

// Normalizing the trailing slash based on the `trailingSlash` configuration
// property from the Next.js config.
if (nextConfig?.trailingSlash && url.pathname !== '/' && !url.pathname.endsWith('/')) {
url.pathname = `${url.pathname}/`
if (nextConfig?.trailingSlash) {
pathname = addTrailingSlash(pathname)
}
}

if (didRemoveBasePath) {
url.pathname = addBasePath(url.pathname, nextConfig?.basePath)
}

// keep the locale in the url for request.nextUrl object
if (detectedLocale) {
url.pathname = `/${detectedLocale}${url.pathname}`
}
url.pathname = addBasePath(pathname, nextConfig?.basePath)

return {
url: url.toString(),
Expand Down

0 comments on commit 2326319

Please sign in to comment.