Internationalization

ubean uses vue-i18n 11 (Composition API, legacy: false) on the Vue side and @intlify/core in Hono handlers. Language routing is compact prefixes compiled once by compileLocalePaths() and shared by vue-router and Hono.

useI18n comes from vue-i18n directly (auto-import requires autoImports: { vueI18n: true } in ubean.config.ts — off by default; otherwise import it explicitly); destructure t from the returned composer. Framework helpers like setLocale are imported from ubean/client.

Setup

Configure everything in ubean.config.ts. Middleware is mounted by createUbeanApp automatically — you do not need src/middleware/02.i18n.ts.

// ubean.config.ts
import { defineConfig } from 'ubean';

export default defineConfig({
  i18n: {
    defaultLocale: 'en',
    locales: [
      { code: 'en', language: 'en', name: 'English' },
      { code: 'zh', language: 'zh-CN', name: '简体中文' }
    ],
    strategy: 'prefix_except_default',
    baseUrl: 'https://example.com',
    detectBrowserLanguage: {
      cookieName: 'ubean_locale',
      redirectOn: 'root' // default
    },
    vueI18n: {
      fallbackLocale: 'en'
    }
  }
});

locales: ['en', 'zh'] is normalized to { code } objects. i18n: false (or empty locales) disables routing and middleware.

language is BCP 47 for <html lang> and hreflang. Locale codes are reserved URL segments: pages/[id].vue will not match /zh if zh is a locale code.

BCP-47 code, short URL segment

code is the locale’s identity: cookies, message catalogs, <html lang>, hreflang, and whatever you pass to component libraries (@vean/ui’s SConfigProvider). Make it a full BCP-47 tag (zh-CN, pt-BR).

When you also want short URLs, add path:

i18n: {
  locales: [
    { code: 'en' },                                  // URL: /about
    { code: 'zh-CN', path: 'zh', name: '简体中文' },  // URL: /zh/about
    { code: 'pt-BR', path: 'pt' }                    // URL: /pt/about
  ],
  defaultLocale: 'en',
  strategy: 'prefix_except_default'
}
  • The URL uses path; everything else uses code: Set-Cookie: ubean_locale=zh-CN, Content-Language: zh-CN, <html lang="zh-CN">, hreflang="zh-CN".
  • /zh-CN/about is not reachable (404). /zh/about is the only entry point.
  • Two locales mapping to one segment throws at config load — otherwise the later registration silently shadows the earlier locale’s routes.

Never build links as /${locale}/...; use localizePath() or <Link to> (which localizes to automatically).

Locale files

Put messages in src/locales/**/*.{json,json5,yaml,yml,ts,js}. Syntax is Intlify (not ICU): {name}, @:key, a | b | {n} c.

// src/locales/en.json
{
  "hello": "Hello",
  "welcome": "Welcome to ubean",
  "greeting": "Hello, {name}!",
  "items": "no items | one item | {count} items",
  "app": { "name": "ubean" },
  "linked": "Welcome to @:app.name!"
}

Messages load lazily via loadLocale(code). SSR preloads the current locale + fallback; __UBEAN_LOCALE__ serializes only those two catalogs.

Vue usage

<script setup lang="ts">
const { t, d, n, locale } = useI18n();

async function toZh() {
  await setLocale('zh'); // load + cookie + router.replace
}
</script>

<template>
  <h1>{{ t('hello') }}</h1>
  <p>{{ t('greeting', { name: 'World' }) }}</p>
  <button @click="toZh">中文</button>
  <p>Current: {{ locale }}</p>
</template>

Switch language with framework setLocale, not locale.value = 'zh'. setLocale loads messages, writes the cookie, and navigates (no_prefix skips navigation).

Use getAvailableLocales() for the switcher: it returns { code, path?, name?, dir, isDefault? } — pass code to setLocale, use name as the label. Do not use vue-i18n availableLocales (that list is only loaded catalogs: current + fallback after hydrate), and do not concatenate /${code}/ yourself (wrong whenever path differs from code).

<script setup lang="ts">
const locales = getAvailableLocales();
</script>

<template>
  <button v-for="lc in locales" :key="lc.code" :lang="lc.code" @click="setLocale(lc.code)">
    {{ lc.name ?? lc.code }}
  </button>
</template>

It is a plain function, not a useXxx composable: it reads the globalThis runtime singleton, so it works in router guards, event handlers and SSR.

Paths and <Link>

<script setup lang="ts">
const localePath = useLocalePath();
const switchLocalePath = useSwitchLocalePath();
</script>

<template>
  <Link to="/about">About</Link>
  <!-- zh → /zh/about ; default en → /about -->
  <Link to="/about" locale="en">English About</Link>
</template>

useLocalePath('/about', 'zh') → /zh/about. useSwitchLocalePath('zh') rewrites the current route.

Typed keys

ubean prepare / dev / build generate .ubean/i18n.d.ts from the default locale JSON. It holds data only: DefineLocaleMessage, the nested message tree.

The flattened key union is derived, not emitted: LocaleMessageKey is the leaf-path union of DefineLocaleMessage ('app.title' | 'common.hello' | …), exported by ubean/client.

import type { LocaleMessageKey } from 'ubean/client';

const key = 'common.hello' satisfies LocaleMessageKey; // ok
// @ts-expect-error misspelled key
const typo: LocaleMessageKey = 'common.hellp';

Deriving instead of expanding keeps DefineLocaleMessage the single source: a declare module merge you hand-write under src/ joins the union too, and the generated file does not grow with the number of keys.

declare module 'vue-i18n' {
  export interface DefineLocaleMessage {
    extra: { handWritten: string };
  }
}
// 'extra.handWritten' is now part of LocaleMessageKey

Note that vue-i18n’s own t() does not check keys: Composer['t'] is typed <Key extends string>(key: Key | ResourceKeys | number), and the bare Key accepts any string — its internal ResourceKeys (JsonPaths<DefineLocaleMessage>) only feeds completion. To hard-enforce, funnel keys through LocaleMessageKey before calling t():

function tk(key: LocaleMessageKey) {
  return t(key);
}
tk('common.hello');
tk('common.hellp'); // type error

Do not hand-roll the derivation: @intlify/core-base exports JsonPaths and RemoveIndexSignature — the exact pair vue-i18n uses to derive ResourceKeys — and LocaleMessageKey uses them too (see packages/client/src/i18n.ts). The one thing you must not drop is RemoveIndexSignature: DefineLocaleMessage extends Record<string, …> and therefore carries an index signature, so a bare JsonPaths collapses the union to string and every typo passes. @intlify/core-base is pinned to the same version as vue-i18n in the catalog, and the scaffold defaults to shamefullyHoist: true, so projects resolve it directly.

API routes / handlers

In handlers, t() / d() / n() from ubean/i18n read the request AsyncLocalStorage scope. Outside a request they throw — they never fall back to a process-global locale.

import { defineHandler } from 'ubean/server';
import { t, getRequestLocale } from 'ubean/i18n';

export const GET = defineHandler(c => {
  const locale = getRequestLocale(c);
  return c.json({ locale, hello: t('hello') });
});

/api/, /_, /__ still enter ALS (cookie / Accept-Language) but do not rewrite the URL.

Cloudflare Workers need nodejs_compat for AsyncLocalStorage. If ALS is unavailable, t() throws; read c.get('locale') instead.

Routing strategies

Hono and vue-router share the same compiled paths (defaultLocale: 'en', locales en, zh, page /about):

strategyvue-routerHono
prefix_except_default (default)/:locale(zh)?/about/about, /zh/about (no /en/about)
prefix/:locale(en|zh)/about/en/about, /zh/about
prefix_and_default/:locale(en|zh)?/about/about, /en/about, /zh/about
no_prefix/about/about

Detection order (prefixed strategies): URL prefix → cookie → Accept-Language → defaultLocale. Cookie is written. Default redirectOn: 'root': only / 302s from Accept-Language; /about does not. prefix still 302s unprefixed content regardless of redirectOn.

SEO

SSR HTML automatically sets:

  • <html lang> / <html dir>
  • link rel="alternate" hreflang (including language-group catch-all and x-default)
  • canonical (prefix_and_default points the default locale at the unprefixed URL)
  • og:locale / og:locale:alternate

useLocaleHead() updates head after client-side locale switches. Set i18n.baseUrl for absolute hreflang hrefs.