11import { NextConfig } from "config/index.js" ;
2- import type { i18nConfig } from "types/next-types" ;
2+ import type { DomainLocale , i18nConfig } from "types/next-types" ;
33import type { InternalEvent } from "types/open-next" ;
44
55import { debug } from "../../../adapters/logger.js" ;
@@ -20,6 +20,31 @@ function getLocaleFromCookie(cookies: Record<string, string>) {
2020 : undefined ;
2121}
2222
23+ // Inspired by https://github.com/vercel/next.js/blob/canary/packages/next/src/shared/lib/i18n/detect-domain-locale.ts
24+ export function detectDomainLocale (
25+ hostname : string ,
26+ i18n : i18nConfig ,
27+ detectedLocale ?: string ,
28+ ) : DomainLocale | undefined {
29+ if ( i18n . localeDetection === false ) {
30+ return ;
31+ }
32+ if ( ! i18n . domains ) {
33+ return ;
34+ }
35+ for ( const item of i18n . domains ) {
36+ // We remove the port if present
37+ const domainHostname = item . domain . split ( ":" , 1 ) [ 0 ] . toLowerCase ( ) ;
38+ if (
39+ hostname === domainHostname ||
40+ detectedLocale === item . defaultLocale . toLowerCase ( ) ||
41+ item . locales ?. some ( ( locale ) => detectedLocale === locale . toLowerCase ( ) )
42+ ) {
43+ return item ;
44+ }
45+ }
46+ }
47+
2348export function detectLocale (
2449 internalEvent : InternalEvent ,
2550 i18n : i18nConfig ,
@@ -39,9 +64,14 @@ export function detectLocale(
3964 defaultLocale : i18n . defaultLocale ,
4065 } ) ;
4166
42- return cookiesLocale ?? preferredLocale ?? i18n . defaultLocale ;
67+ const domainLocale = detectDomainLocale ( internalEvent . headers . host , i18n ) ;
4368
44- // TODO: handle domain based locale detection
69+ return (
70+ domainLocale ?. defaultLocale ??
71+ cookiesLocale ??
72+ preferredLocale ??
73+ i18n . defaultLocale
74+ ) ;
4575}
4676
4777export function localizePath ( internalEvent : InternalEvent ) : string {
@@ -52,6 +82,17 @@ export function localizePath(internalEvent: InternalEvent): string {
5282 if ( isLocalizedPath ( internalEvent . rawPath ) ) {
5383 return internalEvent . rawPath ;
5484 }
85+ const preferredLocale = acceptLanguage (
86+ internalEvent . headers [ "accept-language" ] ,
87+ i18n ?. locales ,
88+ ) ;
89+
5590 const detectedLocale = detectLocale ( internalEvent , i18n ) ;
91+
92+ // not entirely sure if we should do that or not here
93+ if ( preferredLocale && preferredLocale !== detectedLocale ) {
94+ return `/${ preferredLocale } ${ internalEvent . rawPath } ` ;
95+ }
96+
5697 return `/${ detectedLocale } ${ internalEvent . rawPath } ` ;
5798}
0 commit comments