Localeo
All guides

Vue localization with vue-i18n and Localeo

Connect a Vue 3 app built with Vite to a Localeo release using vue-i18n. You’ll download Localeo’s JSON files at build time, load each language on demand, and learn which characters vue-i18n treats as syntax, so your translators know what to type.

Framework
Vue 3.5 + Vite 8, vue-i18n 11.4 (also run on 10.0)
Format
JSON
Time
15 minutes
  1. Find your release files

    In Localeo, open your project and go to Releases. Every published release has a download link per language and format, and there is also a latest link that always points at the newest published release. You’ll use the JSON links:

    bash
    # a pinned release: never changes, cached for a yearhttps://cdn.localeo.app/p/<projectSlug>/r/<releaseSlug>/<lang>.json # the newest published release: cached for about a minute, refreshed on publishhttps://cdn.localeo.app/p/<projectSlug>/r/latest/<lang>.json

    Each file is a flat JSON object keyed by your keys exactly as you wrote them. Keys often contain dots, but they are not nested:

    nl.json
    {  "app.title": "Acme Winkel",  "cart.greeting": "Hoi {name}, welkom terug!",  "cart.items": "{count} artikel | {count} artikelen",  "checkout.pay_button": "Nu {amount} betalen",  "support.contact": "Vragen? Mail support{'@'}acme.com"}

    Localeo ships every value byte for byte, so these values are already written in vue-i18n’s own syntax. More on that below. A key with no translation in a language is left out of that language’s file, so your app needs to fall back to the base language. A publish includes every value, drafts too.

  2. Download a release at build time

    bash
    npm install vue-i18n

    Put the CDN base, your project slug and the release slug in .env. Pin a release slug for reproducible builds; latest works too if you’d rather pick up whatever was published last each time you build.

    .env
    LOCALEO_CDN_URL=https://cdn.localeo.appLOCALEO_PROJECT=<projectSlug>LOCALEO_RELEASE=<releaseSlug>

    A small Node script saves one file per language into src/locales/. These variables have no VITE_ prefix, so Vite never puts them in your bundle.

    scripts/fetch-locales.mjs
    // Downloads a Localeo release into src/locales/, so it ships inside the bundle.import { mkdir, writeFile } from "node:fs/promises"; const LANGUAGES = ["en", "nl", "pt-BR"]; // keep in sync with src/i18n.ts const { LOCALEO_CDN_URL, LOCALEO_PROJECT, LOCALEO_RELEASE } = process.env;if (!LOCALEO_CDN_URL || !LOCALEO_PROJECT || !LOCALEO_RELEASE) {  throw new Error("Set LOCALEO_CDN_URL, LOCALEO_PROJECT and LOCALEO_RELEASE");}const release = `${LOCALEO_CDN_URL}/p/${LOCALEO_PROJECT}/r/${LOCALEO_RELEASE}`; await mkdir("src/locales", { recursive: true });await Promise.all(  LANGUAGES.map(async (lang) => {    const res = await fetch(`${release}/${lang}.json`);    // Only the file name: the URL contains your project slug.    if (!res.ok) throw new Error(`${lang}.json: HTTP ${res.status}`);    await writeFile(`src/locales/${lang}.json`, await res.text());  }),);

    Run it before every dev server start and every build:

    package.json
    "scripts": {  "locales": "node --env-file-if-exists=.env scripts/fetch-locales.mjs",  "predev": "npm run locales",  "dev": "vite",  "prebuild": "npm run locales",  "build": "vue-tsc -b && vite build"}
  3. Create the i18n instance and load languages

    src/i18n.ts
    import { createI18n } from "vue-i18n"; export const BASE_LANGUAGE = "en"; // your Localeo project's base languageexport const LANGUAGES = ["en", "nl", "pt-BR"]; export const i18n = createI18n({  legacy: false,  locale: BASE_LANGUAGE,  fallbackLocale: BASE_LANGUAGE,  messages: {},}); async function loadMessages(lang: string) {  if (i18n.global.availableLocales.includes(lang)) return;  // Downloaded by scripts/fetch-locales.mjs; Vite emits one chunk per language.  const { default: file } = await import(`./locales/${lang}.json`);  const messages: Record<string, string> = { ...file };  i18n.global.setLocaleMessage(lang, messages);   // vue-i18n throws inside t() on a value it can't parse, such as a bare @.  // Drop those, so the key falls back to the base language instead.  for (const key of Object.keys(messages)) {    try {      i18n.global.t(key, {}, { locale: lang });    } catch {      console.warn(`[localeo] ${lang} "${key}" is not valid vue-i18n syntax`);      delete messages[key];    }  }  i18n.global.setLocaleMessage(lang, messages);} export async function setLanguage(lang: string) {  await loadMessages(BASE_LANGUAGE); // the fallback for keys a language omits  await loadMessages(lang);  i18n.global.locale.value = lang;  document.documentElement.lang = lang;}
    • fallbackLocale is your Localeo base language, and setLanguage always loads it first. When pt-BR.json has no checkout.pay_button, vue-i18n uses the English value.
    • Dotted keys work as they are. When vue-i18n can’t walk cart.items as a path, it looks the whole string up as a key, so you don’t need the flatJson option. We tested both; flatJson: true rewrites the object into a tree, and warns and keeps the key flat when a key such as cart is also a prefix of cart.items.
    • The dynamic import() makes Vite emit one small chunk per language, so users only download the language they’re looking at.
    • The loop over messages protects you from a value vue-i18n can’t parse. In vue-i18n 11 such a value throws inside t() and takes the component down with it. Dropped keys fall back to the base language, and a warning names them.

    Load the saved or base language before mounting, so the first render is translated:

    src/main.ts
    import { createApp } from "vue";import App from "./App.vue";import { BASE_LANGUAGE, i18n, LANGUAGES, setLanguage } from "./i18n"; const saved = localStorage.getItem("lang");await setLanguage(saved && LANGUAGES.includes(saved) ? saved : BASE_LANGUAGE);createApp(App).use(i18n).mount("#app");
  4. Write values in vue-i18n’s syntax

    vue-i18n doesn’t use ICU MessageFormat. It has its own syntax, and Localeo delivers values exactly as typed, so the people writing translations in Localeo need to use it:

    • Placeholders are the same as in Localeo: Hoi {name}.
    • Plurals are forms separated by a pipe: {count} artikel | {count} artikelen. With three forms the first is used for zero: geen artikelen | {count} artikel | {count} artikelen. The count is available as both {count} and {n}.
    • @, |, { and } are syntax. To show one as text, wrap it in a literal: support{'@'}acme.com, ma {'|'} di {'|'} wo, {'{'}.

    What happens when a value doesn’t follow these rules, tested with vue-i18n 11:

    • A bare @, as in support@acme.com or Meet @ noon, is read as the start of a linked message and fails with “Invalid linked format”. The loader drops it, so users see the base-language value.
    • A bare | silently turns the value into a plural: Shop | Cart renders as Shop. Nothing warns you about this one.
    • An ICU plural such as {count, plural, one {# item} other {# items}} fails with “Invalid token in placeholder”. If your values already use ICU, see the next step.

    In components, pass placeholder values as an object and the plural count as a number:

    src/App.vue
    <script setup lang="ts">import { useI18n } from "vue-i18n";import { LANGUAGES, setLanguage } from "./i18n"; const { t, locale } = useI18n(); async function choose(event: Event) {  const lang = (event.target as HTMLSelectElement).value;  await setLanguage(lang);  localStorage.setItem("lang", lang);}</script> <template>  <select :value="locale" @change="choose">    <option v-for="lang in LANGUAGES" :key="lang">{{ lang }}</option>  </select>   <h1>{{ t("app.title") }}</h1>  <p>{{ t("cart.greeting", { name: "Sam" }) }}</p>  <p>{{ t("cart.items", 1) }}</p>  <p>{{ t("cart.items", 5) }}</p>  <button type="button">    {{ t("checkout.pay_button", { amount: "€12.50" }) }}  </button>  <p>{{ t("support.contact") }}</p></template>

    In Dutch this renders “Hoi Sam, welkom terug!”, then “1 artikel” and “5 artikelen”, and the support line shows support@acme.com. In Brazilian Portuguese the pay button reads “Pay €12.50 now”, because that key is missing from pt-BR.json.

  5. Already writing ICU plurals? Swap the message compiler

    If the same Localeo project also feeds an app that expects ICU, say a Flutter app or a React app with i18next, you can keep ICU values and teach vue-i18n to read them with intl-messageformat:

    bash
    npm install intl-messageformat
    src/messageCompiler.ts
    import { IntlMessageFormat } from "intl-messageformat";import type { CompileError, MessageCompiler, MessageContext } from "vue-i18n"; // Reads values as ICU MessageFormat instead of vue-i18n's own syntax.export const messageCompiler: MessageCompiler = (message, { locale, key, onError }) => {  if (typeof message !== "string") return () => key; // Localeo values are strings  try {    const formatter = new IntlMessageFormat(message, locale);    return (ctx: MessageContext) => {      try {        return String(formatter.format(ctx.values));      } catch {        return key; // a missing argument shows the key instead of breaking the render      }    };  } catch (err) {    onError?.(err as CompileError);    return () => key;  }};
    src/i18n.ts
    import { createI18n } from "vue-i18n";import { messageCompiler } from "./messageCompiler"; export const i18n = createI18n({  legacy: false,  locale: BASE_LANGUAGE,  fallbackLocale: BASE_LANGUAGE,  messageCompiler, // values are ICU MessageFormat now  messages: {},});

    Plurals then take the count as a named value, t("cart.items", { count: 5 }), and @ and | are plain text again. The loader from step 3 still drops values that aren’t valid ICU, such as an unclosed brace.

  6. Or load the latest release at runtime

    Bundling a pinned release gives you reproducible builds: what you tested is what ships. The trade-off is that a copy change needs a rebuild. If you’d rather pick up new translations without redeploying, load the latest files at runtime. They’re cached for about a minute, so a publish shows up shortly after.

    Drop the predev and prebuild scripts, and in src/i18n.ts replace the dynamic import() and the line after it with a fetch from your own origin:

    src/i18n.ts
      const res = await fetch(`/locales/${lang}.json`); // proxied to the CDN, see vite.config.ts  if (!res.ok) throw new Error(`${lang}.json: HTTP ${res.status}`);  const messages: Record<string, string> = await res.json();

    Vite proxies that path to Localeo’s latest files:

    vite.config.ts
    import vue from "@vitejs/plugin-vue";import { defineConfig, loadEnv } from "vite"; export default defineConfig(({ mode }) => {  const env = loadEnv(mode, process.cwd(), "LOCALEO_"); // server-side only, never in the bundle  const proxy = {    "/locales": {      target: env.LOCALEO_CDN_URL,      changeOrigin: true,      rewrite: (path: string) =>        path.replace(/^\/locales/, `/p/${env.LOCALEO_PROJECT}/r/latest`),    },  };  return { plugins: [vue()], server: { proxy }, preview: { proxy } };});

    That covers npm run dev and npm run preview. In production, set up the same rewrite on whatever serves your app: /locales/* to https://cdn.localeo.app/p/<projectSlug>/r/latest/*. Most static hosts and reverse proxies support this. In nginx, for example:

    nginx.conf
    location /locales/ {  proxy_pass https://cdn.localeo.app/p/<projectSlug>/r/latest/;  proxy_ssl_server_name on;}
  7. Next steps

    • Read how releases, the latest link and caching work in Releases and bundles.
    • Using pinned releases? Subscribe to the release_published webhook and trigger a rebuild in CI, so a publish in Localeo ends up in your next deploy without anyone copying files around.
    • Adding a language in Localeo? Add it to the language list in both scripts/fetch-locales.mjs and src/i18n.ts.

Ship it with Localeo

Create a project, add your languages and publish your first release. Then point this setup at its links.

Get started