diff --git a/packages/next/server/web/next-url.ts b/packages/next/server/web/next-url.ts index 0b95d64060cf..9ce906c83849 100644 --- a/packages/next/server/web/next-url.ts +++ b/packages/next/server/web/next-url.ts @@ -102,7 +102,8 @@ export class NextURL { if ( this[Internal].locale?.locale && - i18n?.defaultLocale !== this[Internal].locale?.locale + i18n?.defaultLocale !== this[Internal].locale?.locale && + !this.hasPathPrefix('/api') ) { pathname = `/${this[Internal].locale?.locale}${pathname}` } @@ -114,6 +115,11 @@ export class NextURL { return pathname } + private hasPathPrefix(prefix: string) { + const pathname = this[Internal].url.pathname + return pathname === prefix || pathname.startsWith(prefix + '/') + } + public get locale() { return this[Internal].locale?.locale ?? '' } diff --git a/test/unit/web-runtime/next-url.test.ts b/test/unit/web-runtime/next-url.test.ts index ed13e63eb217..7ad6ac56aaff 100644 --- a/test/unit/web-runtime/next-url.test.ts +++ b/test/unit/web-runtime/next-url.test.ts @@ -188,3 +188,25 @@ it('allows to clone a new copy', () => { expect(url.toString()).toEqual('http://localhost/root/es/bar') expect(clone.toString()).toEqual('http://localhost/root-test/es/test') }) + +it('does not add locale for api route', () => { + const url = new NextURL('http:///localhost:3000/api', { + i18n: { + defaultLocale: 'en', + locales: ['en', 'es', 'fr'], + }, + }) + url.locale = 'fr' + + let expected = 'http://localhost:3000/api' + expect(url.href).toEqual(expected) + expect(url.toString()).toEqual(expected) + expect(url.toJSON()).toEqual(expected) + + url.pathname = '/api/hello' + + expected = 'http://localhost:3000/api/hello' + expect(url.href).toEqual(expected) + expect(url.toString()).toEqual(expected) + expect(url.toJSON()).toEqual(expected) +})