Skip to content

Commit

Permalink
fix: Support relative pathnames in redirect (#1178)
Browse files Browse the repository at this point in the history
Fixes #1177
  • Loading branch information
amannn committed Jul 9, 2024
1 parent cb005a5 commit 3b698d7
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
9 changes: 7 additions & 2 deletions packages/next-intl/src/navigation/shared/redirects.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import {
} from 'next/navigation';
import {Locales, LocalePrefixConfigVerbose} from '../../routing/types';
import {ParametersExceptFirst} from '../../shared/types';
import {getLocalePrefix, isLocalHref, prefixPathname} from '../../shared/utils';
import {
getLocalePrefix,
isLocalizableHref,
prefixPathname
} from '../../shared/utils';

function createRedirectFn(redirectFn: typeof nextRedirect) {
return function baseRedirect<AppLocales extends Locales>(
Expand All @@ -17,7 +21,8 @@ function createRedirectFn(redirectFn: typeof nextRedirect) {
) {
const prefix = getLocalePrefix(params.locale, params.localePrefix);
const localizedPathname =
params.localePrefix.mode === 'never' || !isLocalHref(params.pathname)
params.localePrefix.mode === 'never' ||
!isLocalizableHref(params.pathname)
? params.pathname
: prefixPathname(prefix, params.pathname);
return redirectFn(localizedPathname, ...args);
Expand Down
4 changes: 2 additions & 2 deletions packages/next-intl/src/shared/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import {Locales, LocalePrefixConfigVerbose} from '../routing/types';

type Href = ComponentProps<typeof NextLink>['href'];

export function isRelativeHref(href: Href) {
function isRelativeHref(href: Href) {
const pathname = typeof href === 'object' ? href.pathname : href;
return pathname != null && !pathname.startsWith('/');
}

export function isLocalHref(href: Href) {
function isLocalHref(href: Href) {
if (typeof href === 'object') {
return href.host == null && href.hostname == null;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,12 @@ describe.each([
expect(nextRedirect).toHaveBeenLastCalledWith('/en');
});

it('can redirect to a relative pathname', () => {
vi.mocked(useNextPathname).mockImplementation(() => '/en/about');
render(<Component href="test" />);
expect(nextRedirect).toHaveBeenCalledWith('test');
});

it('can redirect for a non-default locale', () => {
vi.mocked(useParams).mockImplementation(() => ({locale: 'en-gb'}));
vi.mocked(getRequestLocale).mockImplementation(() => 'en-gb');
Expand Down

0 comments on commit 3b698d7

Please sign in to comment.