diff --git a/packages/next-intl/src/navigation/utils.tsx b/packages/next-intl/src/navigation/utils.tsx index 80cd6e731..713640ebc 100644 --- a/packages/next-intl/src/navigation/utils.tsx +++ b/packages/next-intl/src/navigation/utils.tsx @@ -106,8 +106,9 @@ export function compileLocalizedPathname({ function compilePath( namedPath: Pathnames[keyof Pathnames] ) { - let compiled = + const template = typeof namedPath === 'string' ? namedPath : namedPath[locale]; + let compiled = template; if (params) { Object.entries(params).forEach(([key, value]) => { @@ -122,6 +123,15 @@ export function compileLocalizedPathname({ }); } + if (process.env.NODE_ENV !== 'production' && compiled.includes('[')) { + // Next.js throws anyway, therefore better provide a more helpful error message + throw new Error( + `Insufficient params provided for localized pathname.\nTemplate: ${template}\nParams: ${JSON.stringify( + params + )}` + ); + } + if (query) { compiled += serializeSearchParams(query); } diff --git a/packages/next-intl/test/navigation/utils.test.tsx b/packages/next-intl/test/navigation/utils.test.tsx index d5c126cd8..bdf2c0eb7 100644 --- a/packages/next-intl/test/navigation/utils.test.tsx +++ b/packages/next-intl/test/navigation/utils.test.tsx @@ -1,5 +1,8 @@ import {describe, expect, it} from 'vitest'; -import {serializeSearchParams} from '../../src/navigation/utils'; +import { + compileLocalizedPathname, + serializeSearchParams +} from '../../src/navigation/utils'; describe('serializeSearchParams', () => { it('handles strings', () => { @@ -18,3 +21,24 @@ describe('serializeSearchParams', () => { expect(serializeSearchParams({v: ['a', 'b']})).toEqual('?v=a&v=b'); }); }); + +describe('compileLocalizedPathname', () => { + it('throws when params were not resolved', () => { + const locales: ReadonlyArray = ['en']; + expect(() => + // @ts-expect-error -- Purposefully miss a param + compileLocalizedPathname({ + locale: 'en', + pathname: '/test/[one]/[two]', + pathnames: '/test/[one]/[two]', + params: {one: '1'} + }) + ).toThrow( + [ + 'Insufficient params provided for localized pathname.', + 'Template: /test/[one]/[two]', + 'Params: {"one":"1"}' + ].join('\n') + ); + }); +});