Nuxt I18n

repository·main·Indexed 24 days ago

https://github.com/nuxt-modules/i18n

An internationalization module for Nuxt applications that integrates with vue-i18n. It provides features including route localization for static and dynamic routes, SEO tag localization, lazy-loaded translation files, and support for Nuxt Layers.

Tokens
41.9K
Snippets
143
Records
211
Agent score
82%

What's inside @nuxtjs/i18n

  1. Overview of Nuxt i18n features

    main

    The Nuxt i18n module provides several core capabilities for building internationalized Nuxt applications:

    • Vue I18n Integration: Powered by Nuxt 3 for optimal performance and SEO.
    • Automatic Routes Generation: Automatically overrides Nuxt default routes to add locale prefixes to every URL.
    • Search Engine Optimization (SEO): Provides composables to add SEO metadata based on the current locale.
    • Messages Lazy-Loading: Allows lazy-loading only the selected language instead of bundling all translation messages into the main bundle.
    • Locale-Aware Redirection: Includes ready-to-use composables to handle redirections based on the current locale.
    • Locales Specific Domains: Enables setting different domain names for each supported locale.
  2. Overview of Nuxt I18n features

    main

    Nuxt I18n provides internationalization capabilities for Nuxt applications, including:

    • Integration with vue-i18n
    • Route localization (both static and dynamic routes)
    • Lazy loading of translation files
    • SEO tag localization
    • Support for Nuxt Layers
  3. Use Vue I18n components for translation, dates, and numbers

    main

    When using @nuxtjs/i18n, you have access to the core components provided by the underlying vue-i18n library. These components allow for advanced interpolation, locale-aware date formatting, and locale-aware number/currency formatting directly within your Vue templates.

    Available components:

    • <i18n-t>: Used for translation interpolation. It allows you to inject message slots into a rendered element.
    • <i18n-d>: Used for datetime formatting. It renders dates and times according to the current locale.
    • <i18n-n>: Used for number formatting. It renders numbers and currencies according to the current locale.
  4. Understand where the `defineI18nLocale` loader runs

    main

    The execution environment of your loader depends on the APIs you use within it:

    1. Standard Loader (Outside Nuxt App): By default, in production, the server runs the loader outside the Nuxt app to serve messages via the messages endpoint. You should only use APIs available in both the server and browser, such as $fetch() and useRuntimeConfig().

    2. Nuxt App Loader (Inside Nuxt App): If your loader calls Nuxt app composables (e.g., useNuxtApp(), useState(), useCookie(), useRequestHeaders()), the loader is moved inside the Nuxt app. This means it runs inside the Nuxt app on both the server and the client, and the locale file itself is included in the client bundle.

    Important Constraints:

    • Nitro-only APIs: Utilities like h3 or useStorage() are not available in the browser and will fail if the loader is intended to run in the client.
    • Detection: To ensure a loader stays inside the Nuxt app, you must call the Nuxt composables directly within the locale file. If you call them through an imported helper, they may not be detected at build time, causing the server-side load to fail.
    • SSR/Client Behavior: When using Nuxt composables, messages are produced per request during SSR and again in the browser. Avoid using these if your loader needs to access server-only resources like a database.
    export default defineI18nLocale(async locale => {
      // loaded in the Nuxt app, not through the messages endpoint
      const { $tenant } = useNuxtApp()
      return $fetch(`/api/messages/${$tenant.id}/${locale}`)
    })
  5. How Nuxt i18n layers work

    main

    Nuxt i18n supports Nuxt layers, automatically combining i18n configurations from all extended layers.

    Merging Strategy

    Following the standard Nuxt layer priority, earlier items in the _layers array have higher priority and override later ones. The user's main project is always the first item in the array, meaning it has the highest priority.

    Pages & Routing

    • Pages: Files in the pages directory of extended layers are automatically merged and receive full i18n support.
    • Routing: Page routes defined in the i18n.pages configuration of each layer are merged together.

    VueI18n Options

    Options defined in the VueI18n configuration within layers are merged, with higher-priority layers overriding those in lower-priority layers.

  6. Best practices for <NuxtLinkLocale> routing

    main

    While <NuxtLinkLocale> supports passing raw path strings (e.g., to="/"), it is highly recommended to use named routes instead.

    Why? Path strings depend on your configured strategy and custom paths. A path that works now might break if your routing configuration changes. When typedPages is enabled in Nuxt, the to prop on <NuxtLinkLocale> is type-checked to only accept named routes, helping prevent these silent failures.

  7. Restrict locales to specific domains

    main

    You can restrict a locale to only be served on specific domains by providing a domains array in its configuration. This is useful for ensuring each page is reachable at a single canonical URL. If a user attempts to access a restricted locale on a domain where it is not listed, they will be redirected to the correct domain.

    Using strategy: 'no_prefix': When using the no_prefix strategy, each domain must serve exactly one locale. If two locales share a domain under this strategy, it will result in unlocalized routes and a build-time error.

    export default defineNuxtConfig({
      i18n: {
        locales: [
          {
            code: 'en',
            domains: ['mydomain.com'],
            defaultForDomains: ['mydomain.com']
          },
          {
            code: 'fr',
            domains: ['mydomain.com', 'es.mydomain.com']
          },
          {
            code: 'es',
            domains: ['es.mydomain.com'],
            defaultForDomains: ['es.mydomain.com']
          }
        ],
        defaultLocale: 'en',
        strategy: 'prefix_except_default',
        multiDomainLocales: true
      }
    })
  8. How `defaultLocale` and `x-default` work with multi-domain locales

    main

    When using multiple domains, Nuxt i18n treats domains as clusters where pages link to their alternates on other domains. To ensure consistency across the cluster, the x-default alternate is derived from the defaultLocale configuration rather than the default locale of an individual domain. This prevents different domains from claiming different x-default values for the same cluster.

    Note: defaultLocale is optional. If omitted, no x-default signal is annotated. While allowed, this drops the signal for visitors whose language matches none of your configured locales, and a warning will be logged.

  9. How locale advertisement and canonical links work in multi-domain setups

    main

    In a multi-domain configuration, a locale served on several domains is 'advertised' (annotated) on only one of them to maintain reciprocal cluster links.

    • Which domain is chosen?: The first entry in the locale's defaultForDomains list is used. If defaultForDomains is not provided, the first entry in the locale's domains list is used.
    • Behavior: Every domain serving that locale will emit the same URL for it. This ensures the cluster remains reciprocal.
    • Canonical Links: A page reachable on multiple domains will point its canonical link to the URL where its language is officially advertised, rather than claiming itself as the canonical source.
    • Locales without domains: If a locale is configured without any specific domain, it is served on all domains but has no domain of its own to be annotated on; it defaults to using the domain serving the defaultLocale.

    Best Practice: Because a locale is only advertised on one domain even if reachable on others, you should restrict a locale to its specific domain unless you explicitly intend for it to be served across multiple domains.

  10. Nitro-side language detection and redirection

    main

    Language detection and redirection are now handled by the Nitro server. This improves performance by allowing redirects earlier in the request lifecycle and ensures compatibility with prerendering.

    If this causes issues in your project, you can temporarily disable it by setting experimental.nitroContextDetection: false in your module options.

  11. Configure cookie domain for cross-domain language detection

    main
    When your domains share a common suffix (e.g., subdomains like en.example.com and fr.example.com), you should set detectBrowserLanguage.cookieDomain to that suffix. This allows the visitor's locale choice to persist as they navigate between different domains. A cookie scoped to a single domain will not trigger redirects on other domains.