Skip to content

Commit

Permalink
fix: do not add locale prefix to api route on NextURL (#36118)
Browse files Browse the repository at this point in the history
Fixes #35694

## Bug

- [x] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
  • Loading branch information
nkzawa committed Apr 13, 2022
1 parent 4bf01d4 commit 1d8165b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
8 changes: 7 additions & 1 deletion packages/next/server/web/next-url.ts
Expand Up @@ -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}`
}
Expand All @@ -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 ?? ''
}
Expand Down
22 changes: 22 additions & 0 deletions test/unit/web-runtime/next-url.test.ts
Expand Up @@ -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)
})

0 comments on commit 1d8165b

Please sign in to comment.