amannn / next-intl

🌐 Internationalization (i18n) for Next.js
https://next-intl-docs.vercel.app
MIT License
2.58k stars 236 forks source link

feat: Add `defineRouting` for easier i18n routing setup #1299

Closed amannn closed 2 months ago

amannn commented 2 months ago

Summary

Adds a new defineRouting API that returns a routing object that can be used to initialize the middleware as well as the navigation APIs. This provides type-safety for your i18n config with a single import and helps to ensure that your i18n config is in sync across your app.

// routing.ts

import {defineRouting} from 'next-intl/routing';

export const routing = defineRouting({
  locales: ['en-US', 'en-GB'],
  defaultLocale: 'en-US',
  localePrefix: {
    mode: 'always',
    prefixes: {
      'en-US': '/us',
      'en-GB': '/uk'
    }
  },
  pathnames: {
    '/': '/',
    '/organization': {
      'en-US': '/organization',
      'en-GB': '/organisation'
    }
  }
});
// middleware.ts

import createMiddleware from 'next-intl/middleware';
import {routing} from './routing';

export default createMiddleware(routing);
// navigation.ts

import {createSharedPathnamesNavigation} from 'next-intl/navigation';
import {routing} from './routing';

export const {Link, redirect, usePathname, useRouter} =
  createSharedPathnamesNavigation(routing);

While this change is purely additional, it's encouraged to adopt defineRouting in existing code bases and the docs have been updated to reflect this.

Migration example: https://github.com/amannn/next-intl-bug-repro-app-router/commit/0a0068405bc4e23825fd1cd593f3232ead996983

In case you're providing either alternateLinks or localeDetection to createMiddleware, these options can now be passed as a second argument:

createMiddleware(routing, {
  alternateLinks: false,
  localeDetection: false
});

Changes

vercel[bot] commented 2 months ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
next-intl-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 28, 2024 2:43pm
next-intl-example-app-router ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 28, 2024 2:43pm
next-intl-example-app-router-without-i18n-routing ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 28, 2024 2:43pm