Skip to content

Commit

Permalink
fix: Correctly detect base path at the app root / when using a loca…
Browse files Browse the repository at this point in the history
…le prefix strategy other than `always`. This ensures the locale cookie is set correctly. (#999)

Fixes #997
  • Loading branch information
amannn committed Apr 17, 2024
1 parent e66bbce commit 1ce5988
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
4 changes: 2 additions & 2 deletions packages/next-intl/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,11 @@
},
{
"path": "dist/production/navigation.react-client.js",
"limit": "2.94 KB"
"limit": "2.96 KB"
},
{
"path": "dist/production/navigation.react-server.js",
"limit": "3.03 KB"
"limit": "3.06 KB"
},
{
"path": "dist/production/server.react-client.js",
Expand Down
11 changes: 9 additions & 2 deletions packages/next-intl/src/navigation/shared/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,13 @@ export function getRoute<Locales extends AllLocales>({
return template as keyof Pathnames<Locales>;
}

export function getBasePath(pathname: string) {
return window.location.pathname.replace(pathname, '');
export function getBasePath(
pathname: string,
windowPathname = window.location.pathname
) {
if (pathname === '/') {
return windowPathname;
} else {
return windowPathname.replace(pathname, '');
}
}
19 changes: 19 additions & 0 deletions packages/next-intl/test/navigation/shared/utils.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {describe, expect, it} from 'vitest';
import {
compileLocalizedPathname,
getBasePath,
serializeSearchParams
} from '../../../src/navigation/shared/utils';

Expand Down Expand Up @@ -42,3 +43,21 @@ describe('compileLocalizedPathname', () => {
);
});
});

describe('getBasePath', () => {
it('detects a base path when using a locale prefix and the user is at the root', () => {
expect(getBasePath('/en', '/base/en')).toBe('/base');
});

it('detects a base path when using a locale prefix and the user is at a nested path', () => {
expect(getBasePath('/en/about', '/base/en/about')).toBe('/base');
});

it('detects a base path when using no locale prefix and the user is at the root', () => {
expect(getBasePath('/', '/base')).toBe('/base');
});

it('detects a base path when using no locale prefix and the user is at a nested path', () => {
expect(getBasePath('/about', '/base/about')).toBe('/base');
});
});

0 comments on commit 1ce5988

Please sign in to comment.