Getting Started Internationalizing (i18n) with Intlayer and Nuxt
See Application Template on GitHub.
What is Intlayer?
Intlayer is an innovative, open-source internationalization (i18n) library designed to simplify multilingual support in modern web applications.
With Intlayer, you can:
- Easily manage translations using declarative dictionaries at the component level.
- Dynamically localize metadata, routes, and content.
- Ensure TypeScript support with autogenerated types, improving autocompletion and error detection.
- Benefit from advanced features, like dynamic locale detection and switching.
Step-by-Step Guide to Set Up Intlayer in a Nuxt Application
Step 1: Install Dependencies
Install the necessary packages using npm:
npm install intlayer vue-intlayernpm install --save-dev nuxt-intlayer
intlayer
The core package that provides internationalization tools for configuration management, translation, content declaration, transpilation, and CLI commands.
vue-intlayer The package that integrates Intlayer with Vue application. It the composables for the Vue components.
nuxt-intlayer The Nuxt module that integrates Intlayer with Nuxt applications. It provides automatic setup, middleware for locale detection, cookie management, and URL redirection.
Step 2: Configuration of your project
Create a config file to configure the languages of your application:
import { Locales, type IntlayerConfig } from "intlayer";const config: IntlayerConfig = { internationalization: { locales: [ Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH, // Your other locales ], defaultLocale: Locales.ENGLISH, }, content: { contentDir: ["."], // Because by default Intayer will watch content declaration files from the `./src` directory },};export default config;
Through this configuration file, you can set up localized URLs, middleware redirection, cookie names, the location and extension of your content declarations, disable Intlayer logs in the console, and more. For a complete list of available parameters, refer to the configuration documentation.
Step 3: Integrate Intlayer in Your Nuxt Configuration
Add the intlayer module to your Nuxt configuration:
import { defineNuxtConfig } from "nuxt/config";export default defineNuxtConfig({ // ... Your existing Nuxt configuration modules: ["nuxt-intlayer"],});
The nuxt-intlayer module automatically handles the integration of Intlayer with Nuxt. It sets up the content declaration building, monitors files in development mode, provides middleware for locale detection, and manages localized routing.
Step 4: Declare Your Content
Create and manage your content declarations to store translations:
import { t, type Dictionary } from "intlayer";const helloWorldContent = { key: "helloworld", content: { count: t({ en: "count is ", fr: "le compte est ", es: "el recuento es " }), edit: t({ en: "Edit <code>components/HelloWorld.vue</code> and save to test HMR", fr: "Éditez <code>components/HelloWorld.vue</code> et enregistrez pour tester HMR", es: "Edita <code>components/HelloWorld.vue</code> y guarda para probar HMR", }), checkOut: t({ en: "Check out ", fr: "Vérifiez ", es: "Compruebe " }), nuxtIntlayer: t({ en: "Nuxt Intlayer documentation", fr: "Documentation de Nuxt Intlayer", es: "Documentación de Nuxt Intlayer", }), learnMore: t({ en: "Learn more about Nuxt in the ", fr: "En savoir plus sur Nuxt dans la ", es: "Aprenda más sobre Nuxt en la ", }), nuxtDocs: t({ en: "Nuxt Documentation", fr: "Documentation Nuxt", es: "Documentación de Nuxt", }), readTheDocs: t({ en: "Click on the Nuxt logo to learn more", fr: "Cliquez sur le logo Nuxt pour en savoir plus", es: "Haga clic en el logotipo de Nuxt para obtener más información", }), },} satisfies Dictionary;export default helloWorldContent;
Your content declarations can be defined anywhere in your application as long as they are included in the contentDir directory (by default, ./src). And match the content declaration file extension (by default, .content.{json,ts,tsx,js,jsx,mjs,mjx,cjs,cjx}).
For more details, refer to the content declaration documentation.
Step 5: Utilize Intlayer in Your Code
Access your content dictionaries throughout your Nuxt application using the useIntlayer composable:
<script setup lang="ts">import { ref } from "vue";import { useIntlayer } from "vue-intlayer";defineProps({ msg: String,});const { count, edit, checkOut, nuxtIntlayer, learnMore, nuxtDocs, readTheDocs,} = useIntlayer("helloworld");const countRef = ref(0);</script><template> <h1>{{ msg }}</h1> <div class="card"> <button type="button" @click="countRef++"> <count /> {{ countRef }} </button> <p v-html="edit"></p> </div> <p> <checkOut /> <a href="https://nuxt.com/docs/getting-started/introduction" target="_blank" >Nuxt</a >, <nuxtIntlayer /> </p> <p> <learnMore /> <a href="https://nuxt.com" target="_blank"><nuxtDocs /></a>. </p> <p class="read-the-docs"><readTheDocs /></p> <p class="read-the-docs">{{ readTheDocs }}</p></template>
Accessing Content in Intlayer
Intlayer offers different APIs to access your content:
Component-based syntax (recommended): Use the <myContent />, or <Component :is="myContent" /> syntax to render content as an Intlayer Node. This integrates seamlessly with the Visual Editor and CMS.
String-based syntax: Use {{ myContent }} to render the content as plain text, without Visual Editor support.
Raw HTML syntax: Use <div v-html="myContent" /> to render the content as raw HTML, without Visual Editor support.
Destructuration syntax: The useIntlayer composable returns an Proxy with the content. This proxy can be destructured to access the content while keeping the reactivity.
- Use const content = useIntlayer("myContent"); And {{ content.myContent }} / <content.myContent />.
- Or use const { myContent } = useIntlayer("myContent"); And {{ myContent}} / <myContent/> to destructure the content.
(Optional) Step 6: Change the language of your content
To change the language of your content, you can use the setLocale function provided by the useLocale composable. This function allows you to set the locale of the application and update the content accordingly.
Create a component to switch between languages:
<template> <div class="locale-switcher"> <select v-model="selectedLocale" @change="changeLocale"> <option v-for="loc in availableLocales" :key="loc" :value="loc"> {{ getLocaleName(loc) }} </option> </select> </div></template><script setup lang="ts">import { ref, watch } from "vue";import { getLocaleName } from "intlayer";import { useLocale } from "vue-intlayer";// Get locale information and setLocale functionconst { locale, availableLocales, setLocale } = useLocale();// Track the selected locale with a refconst selectedLocale = ref(locale.value);// Update the locale when the selection changesconst changeLocale = () => setLocale(selectedLocale.value);// Keep the selectedLocale in sync with the global localewatch( () => locale.value, (newLocale) => { selectedLocale.value = newLocale; });</script></template><style scoped>.locale-switcher { margin: 1rem 0;}select { padding: 0.5rem; border-radius: 0.25rem; border: 1px solid #ccc;}</style>
Then, use this component in your pages or layout:
<script setup lang="ts">import { useIntlayer } from "vue-intlayer";import LocaleSwitcher from "~/components/LocaleSwitcher.vue";const content = useIntlayer("app"); // Create related intlayer declaration file</script><template> <div> <header> <LocaleSwitcher /> </header> <main> <NuxtPage /> </main> </div></template>
(Optional) Step 7: Add localized Routing to your application
Nuxt automatically handles localized routing when using the nuxt-intlayer module. This creates routes for each language automatically based on your pages directory structure.
Example:
pages/├── index.vue → /, /fr, /es├── about.vue → /about, /fr/about, /es/about└── contact/ └── index.vue → /contact, /fr/contact, /es/contact
To create a localized page, simply create your Vue files in the pages/ directory:
<script setup lang="ts">import { useIntlayer } from "vue-intlayer";const content = useIntlayer("about");</script><template> <div> <h1>{{ content.title }}</h1> <p>{{ content.description }}</p> </div></template>
The nuxt-intlayer module will automatically:
- Detect the user's preferred locale
- Handle locale switching via URL
- Set the appropriate <html lang=""> attribute
- Manage locale cookies
- Redirect users to the appropriate localized URL
(Optional) Step 8: Creating a Localized Link Component
To ensure that your application's navigation respects the current locale, you can create a custom LocalizedLink component. This component automatically prefixes internal URLs with the current language.
<template> <NuxtLink :to="localizedHref" v-bind="$attrs"> <slot /> </NuxtLink></template><script setup lang="ts">import { computed } from "vue";import { getLocalizedUrl } from "intlayer";import { useLocale } from "vue-intlayer";const props = defineProps({ to: { type: String, required: true, },});const { locale } = useLocale();// Check if the link is externalconst isExternalLink = computed(() => /^https?:\/\//.test(props.to || ""));// Create a localized href for internal linksconst localizedHref = computed(() => isExternalLink.value ? props.to : getLocalizedUrl(props.to, locale.value));</script>
Then use this component throughout your application:
<template> <div> <LocalizedLink to="/about"> {{ content.aboutLink }} </LocalizedLink> <LocalizedLink to="/contact"> {{ content.contactLink }} </LocalizedLink> </div></template><script setup lang="ts">import { useIntlayer } from "vue-intlayer";import LocalizedLink from "~/components/LocalizedLink.vue";const content = useIntlayer("home");</script>
(Optional) Step 9: Handle Metadata and SEO
Nuxt provides excellent SEO capabilities. You can use Intlayer to handle localized metadata:
<script setup lang="ts">import { useSeoMeta } from "nuxt/app";import { getIntlayer } from "intlayer";import { useLocale } from "vue-intlayer";const { locale } = useLocale();const content = getIntlayer("about-meta", locale.value);useSeoMeta({ title: content.title, description: content.description,});</script><template> <div> <h1>{{ content.pageTitle }}</h1> <p>{{ content.pageContent }}</p> </div></template>
Create the corresponding content declaration:
import { t, type Dictionary } from "intlayer";import type { useSeoMeta } from "nuxt/app";const aboutMetaContent = { key: "about-meta", content: { title: t({ en: "About Us - My Company", fr: "À Propos - Ma Société", es: "Acerca de Nosotros - Mi Empresa", }), description: t({ en: "Learn more about our company and our mission", fr: "En savoir plus sur notre société et notre mission", es: "Conozca más sobre nuestra empresa y nuestra misión", }), },} satisfies Dictionary<Parameters<typeof useSeoMeta>[0]>;export default aboutMetaContent;
Configure TypeScript
Intlayer uses module augmentation to get benefits of TypeScript and make your codebase stronger.
Ensure your TypeScript configuration includes the autogenerated types.
{ // ... Your existing TypeScript configurations "include": [ // ... Your existing TypeScript configurations ".intlayer/**/*.ts", // Include the auto-generated types ],}
Git Configuration
It is recommended to ignore the files generated by Intlayer. This allows you to avoid committing them to your Git repository.
To do this, you can add the following instructions to your .gitignore file:
# Ignore the files generated by Intlayer.intlayer
VS Code Extension
To improve your development experience with Intlayer, you can install the official Intlayer VS Code Extension.
Install from the VS Code Marketplace
This extension provides:
- Autocompletion for translation keys.
- Real-time error detection for missing translations.
- Inline previews of translated content.
- Quick actions to easily create and update translations.
For more details on how to use the extension, refer to the Intlayer VS Code Extension documentation.
Go Further
To go further, you can implement the visual editor or externalize your content using the CMS.
Doc History
Version | Date | Changes |
---|---|---|
5.5.10 | 2025-06-29 | Init history |
If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentation