@comvi/nuxt API Reference
@comvi/nuxt is a Nuxt 3 module that provides auto-imported composables, locale-aware routing, lazy-loaded translations, and full SSR support. All composables and the <T> component are available globally without imports. It builds on @comvi/core and re-exports all core APIs.
Verified against @comvi/nuxt@0.3.0.
Module Options
Section titled “Module Options”Configure the module under the comvi key in nuxt.config.ts:
export default defineNuxtConfig({ modules: ['@comvi/nuxt'],
comvi: { defaultLocale: 'en', locales: [ { code: 'en', name: 'English' }, { code: 'de', name: 'Deutsch' }, { code: 'fr', name: 'Francais' }, ], localePrefix: 'as-needed', cdnUrl: 'https://cdn.comvi.io/your-distribution-id', },});Options Reference
Section titled “Options Reference”| Option | Type | Default | Description |
|---|---|---|---|
defaultLocale | string | — | Locale used when no other locale is detected (required) |
locales | (string | LocaleObject)[] | — | Available locales (required). Strings or objects with code, name, and optional dir |
localePrefix | 'always' | 'as-needed' | 'never' | 'as-needed' | Controls whether URLs include a locale prefix |
cdnUrl | string | — | Full CDN URL for loading translations in production |
apiKey | string | — | API key for authenticated requests (dev mode). See security note below. |
apiBaseUrl | string | — | API base URL for loading translations |
defaultNs | string | 'default' | Default namespace for translations |
fallbackLanguage | string | string[] | Same as defaultLocale | Language(s) used when a translation key is missing |
detectBrowserLanguage | object | false | See below | Browser language detection settings. Set to false to disable |
basicHtmlTags | string[] | — | HTML tags allowed in tag interpolation |
setup | string | Auto-detected | Path to a setup file that runs before i18n.init(). Auto-detects ./comvi.setup.* in project root |
Locale Object Format
Section titled “Locale Object Format”| Property | Type | Required | Description |
|---|---|---|---|
code | string | Yes | BCP 47 language code (e.g., en, de, ar) |
name | string | No | Human-readable name (e.g., English, Deutsch) |
dir | 'ltr' | 'rtl' | No | Text direction. Defaults to 'ltr' |
iso | string | No | ISO code for SEO (e.g., en-US). Used in hreflang tags |
Browser Language Detection
Section titled “Browser Language Detection”| Property | Type | Default | Description |
|---|---|---|---|
useCookie | boolean | true | Persist detected locale in a cookie |
cookieName | string | 'i18n_locale' | Cookie name for the persisted locale |
cookieMaxAge | number | 31536000 | Cookie max age in seconds (default: 1 year) |
cookieSecure | boolean | true | Set the Secure flag outside dev mode |
redirectOnFirstVisit | boolean | true | Redirect to detected locale on first visit |
fallbackLocale | string | defaultLocale | Locale when detection fails or returns unsupported locale |
comvi: { detectBrowserLanguage: { useCookie: true, cookieName: 'i18n_locale', redirectOnFirstVisit: true, fallbackLocale: 'en', },}Set detectBrowserLanguage: false to disable automatic detection entirely.
Locale Prefix Modes
Section titled “Locale Prefix Modes”| Mode | Default Locale URL | Other Locale URL | Description |
|---|---|---|---|
as-needed | /about | /de/about | Default locale has no URL prefix |
always | /en/about | /de/about | All locales get a prefix |
never | /about | /about | No URL prefixes; locale set via cookie or header |
Auto-Imported Composables
Section titled “Auto-Imported Composables”All composables are auto-imported by the module. You never need import statements for them.
useI18n(ns?)
Section titled “useI18n(ns?)”The primary composable for translating strings and reading locale state.
<script setup lang="ts">const { t, locale, locales, isLoading } = useI18n();</script>
<template> <h1>{{ t('page.title') }}</h1> <p>Current locale: {{ locale }}</p></template>Signature
Section titled “Signature”useI18n(ns?: string)Pass an optional namespace string to scope all t() calls to that namespace.
Returned Values
Section titled “Returned Values”Reactive state:
| Property | Type | Description |
|---|---|---|
t | (key: string, params?) => string | Translate a key with optional interpolation parameters |
tRaw | (key: string, params?) => TranslationResult | Return structured output for advanced renderers |
locale | Ref<string> | Current language (reactive, writable) |
isLoading | Readonly<Ref<boolean>> | true while translations are being fetched |
isInitializing | Readonly<Ref<boolean>> | true during init() |
translationCache | Readonly<Ref<Readonly<ReadonlyMap<string, FlattenedTranslations>>>> | Translation cache (reactive) |
dir | ComputedRef<"ltr" | "rtl"> | Text direction for the current locale. Useful for RTL layout |
loadedLocales | ComputedRef<string[]> | Reactive list of all loaded locale codes |
activeNamespaces | ComputedRef<string[]> | Reactive list of active namespaces |
defaultNamespace | ComputedRef<string> | Reactive default namespace |
Nuxt-specific:
| Property | Type | Description |
|---|---|---|
locales | Ref<readonly string[]> | Configured locale list from module options (read .value in script) |
defaultLocale | Ref<string> | Configured default locale (read .value in script) |
Methods:
| Method | Type | Description |
|---|---|---|
setLocale | (lang: string) => Promise<void> | Switch language and wait for translations to load |
addTranslations | (translations: Record<string, Record<string, TranslationValue>>) => void | Add translations at runtime |
addActiveNamespace | (ns: string) => Promise<void> | Load a new namespace dynamically |
setFallbackLocale | (locales: string | string[]) => void | Configure fallback locale chain |
onMissingKey | (cb: (key, locale, namespace) => TranslationResult | void) => () => void | Register callback for missing keys (returns unsubscribe) |
onLoadError | (cb: (locale, namespace, error) => void) => () => void | Register callback for load errors (returns unsubscribe) |
clearTranslations | (locale?, namespace?) => void | Clear translations from cache |
reloadTranslations | (locale?, namespace?) => Promise<void> | Force reload from loader |
hasLocale | (locale, namespace?) => ComputedRef<boolean> | Reactive check — re-evaluates when the translation cache changes. Call inside setup() or an effectScope. |
hasTranslation | (key, opts?: { locale?, namespace?, checkFallbacks? }) => ComputedRef<boolean> | Reactive check — re-evaluates when locale or cache changes. Call inside setup() or an effectScope. |
hasLocaleNow | (locale, namespace?) => boolean | Imperative (non-reactive) locale check — plain boolean, safe in event handlers, loops, or outside a reactive scope. |
hasTranslationNow | (key, opts?: { locale?, namespace?, checkFallbacks? }) => boolean | Imperative (non-reactive) translation-existence check — plain boolean, safe outside a reactive scope. |
on | (event, callback) => () => void | Subscribe to i18n events (returns unsubscribe) |
reportError | (error, context?) => void | Report an error to the configured handler |
formatNumber | (value, opts?) => string | Format a number using the current locale |
formatDate | (value, opts?) => string | Format a date using the current locale |
formatCurrency | (value, currency, opts?) => string | Format a number as currency |
formatRelativeTime | (value, unit, opts?) => string | Format a relative time (“2 hours ago”, “in 3 days”) |
useLocalePath()
Section titled “useLocalePath()”Returns a function that generates locale-prefixed paths based on the current locale.
<script setup lang="ts">const localePath = useLocalePath();</script>
<template> <NuxtLink :to="localePath('/about')">About</NuxtLink> <!-- Renders /de/about when locale is "de" --></template>Function Signature
Section titled “Function Signature”const localePath: (path: RouteLocationRaw, locale?: string) => string;| Argument | Type | Default | Description |
|---|---|---|---|
path | RouteLocationRaw | — | The path or route object to prefix (required) |
locale | string | Current locale | Override the locale for the generated path |
useSwitchLocalePath()
Section titled “useSwitchLocalePath()”Returns a function that generates the current page’s URL in a different locale.
<script setup lang="ts">const switchLocalePath = useSwitchLocalePath();</script>
<template> <NuxtLink :to="switchLocalePath('en')">English</NuxtLink> <NuxtLink :to="switchLocalePath('de')">Deutsch</NuxtLink></template>Function Signature
Section titled “Function Signature”const switchLocalePath: (locale: string) => string;useLocaleRoute()
Section titled “useLocaleRoute()”Returns a function that resolves a full route object for a given path and locale. Useful when you need the full RouteLocationResolved object instead of just a path string.
<script setup lang="ts">const localeRoute = useLocaleRoute();
function goToAbout() { const route = localeRoute('/about', 'de'); if (route) { navigateTo(route.fullPath); }}</script>Function Signature
Section titled “Function Signature”const localeRoute: (path: RouteLocationRaw, locale?: string) => RouteLocationResolved | undefined;useLocaleHead(options?)
Section titled “useLocaleHead(options?)”Adds localized <html lang>, dir, canonical URL, alternate hreflang links (with ISO codes when configured), and Open Graph locale meta tags. All options default to true and can be selectively disabled.
<script setup lang="ts">useLocaleHead({ baseUrl: 'https://example.com',});</script>Options
Section titled “Options”| Property | Type | Default | Description |
|---|---|---|---|
baseUrl | string | Auto-detected | Base URL for canonical and alternate links |
addOgLocale | boolean | true | Add og:locale and og:locale:alternate meta tags |
addAlternateLinks | boolean | true | Add hreflang alternate link tags |
addCanonical | boolean | true | Add a canonical <link> tag |
addDir | boolean | true | Set the dir attribute on <html> (requires dir on locale object) |
addLang | boolean | true | Set the lang attribute on <html> |
useRouteConfig()
Section titled “useRouteConfig()”Returns the resolved routing configuration plus helpers for generating localized paths. Useful for sitemap generation and other build-time routing utilities.
const { locales, defaultLocale, localePrefix, getPathname, getAllLocalizedPaths } = useRouteConfig();Returned Values
Section titled “Returned Values”| Property | Type | Description |
|---|---|---|
locales | readonly string[] | Configured locale codes |
defaultLocale | string | Configured default locale |
localePrefix | 'always' | 'as-needed' | 'never' | URL prefix mode |
getPathname | ({ locale, href }) => string | Build a localized pathname |
getAllLocalizedPaths | (href: string) => Array<{ locale, path }> | All localized versions of a path |
export default defineEventHandler(() => { const { locales, getPathname } = useRouteConfig();
const pages = ['/', '/about', '/contact']; const urls = pages.flatMap((page) => locales.map((locale) => ({ loc: `https://example.com${getPathname({ locale, href: page })}`, })) );});Server Utilities
Section titled “Server Utilities”The module auto-imports server utilities into server/ handlers:
| Utility | Signature | Description |
|---|---|---|
useTranslation | (event, options?) => Promise<{ t, locale, hasTranslation }> | Request-scoped server translation helper |
loadTranslations | (event, locale, options?) => Promise<TranslationsResult> | Load namespaces for SSR/SSG payloads |
getRequestI18n | (event, locale) => Promise<I18n> | Get the request-scoped core i18n instance |
getServerRuntimeConfig | (event?) => RuntimeConfig | Read public/private Comvi runtime config on the server |
export default defineEventHandler(async (event) => { const { t, locale } = await useTranslation(event); return { message: t('api.hello'), locale, };});<T> Component
Section titled “<T> Component”Auto-imported. Renders translations with rich content safely using named slots. Same behavior as the @comvi/vue <T> component.
| Prop | Type | Default | Description |
|---|---|---|---|
i18nKey | string | — | Translation key to resolve (required) |
params | Record<string, unknown> | {} | Interpolation parameters |
ns | string | — | Namespace to look up the key in |
locale | string | — | Specific locale to use |
fallback | string | — | Fallback text if the key is missing |
raw | boolean | — | When true, prevents post-processors (such as the in-context editor marker injector) from adding invisible marker characters |
components | Record<string, ComponentHandler> | — | Map of tag names to components (alternative to slots) |
<template> <!-- Translation: "Read our <link>terms of service</link>" --> <T i18nKey="legal.tos"> <template #link="{ children }"> <NuxtLink to="/terms">{{ children }}</NuxtLink> </template> </T></template><NuxtLinkLocale>
Section titled “<NuxtLinkLocale>”A locale-aware replacement for <NuxtLink> that automatically prefixes the to prop with the current locale.
<template> <NuxtLinkLocale to="/about">About Us</NuxtLinkLocale> <!-- Renders <a href="/de/about"> when locale is "de" -->
<NuxtLinkLocale to="/contact" locale="fr">Contact (FR)</NuxtLinkLocale> <!-- Always renders <a href="/fr/contact"> --></template>Inherits all <NuxtLink> props, plus:
| Prop | Type | Default | Description |
|---|---|---|---|
to | string | RouteLocationRaw | — | Target path (will be locale-prefixed, required) |
locale | string | Current locale | Override the locale for the link’s to path |
$t() Global Helper
Section titled “$t() Global Helper”Available in all templates without calling useI18n(). Translates a key with optional parameters.
<template> <footer> <p>{{ $t('footer.copyright', { year: 2025 }) }}</p> </footer></template>Setup Hook
Section titled “Setup Hook”The module auto-discovers ./comvi.setup.ts (or .js) at project root, or specify a path via the setup option. Use defineComviSetup from the @comvi/nuxt/setup subpath for full type inference:
import { defineComviSetup } from '@comvi/nuxt/setup';import { FetchLoader } from '@comvi/plugin-fetch-loader';
export default defineComviSetup(({ i18n, runtimeConfig }) => { i18n.use(FetchLoader({ cdnUrl: runtimeConfig?.public?.comvi?.cdnUrl, }));});The setup function receives a NuxtI18nSetupContext object:
| Property | Type | Description |
|---|---|---|
i18n | VueI18n | I18n | The i18n instance for this runtime (Vue in plugin, core I18n in server utils) |
runtime | 'client' | 'server' | Where the hook is executing |
nuxtApp | NuxtApp? | Available in the runtime plugin |
event | H3Event? | Available in server utilities |
runtimeConfig | RuntimeConfig? | Public + private Nuxt runtime config |
Runs before i18n.init() for both the client plugin and server utility instances.
Runtime Config
Section titled “Runtime Config”Access module config via useRuntimeConfig().public.comvi:
export default defineEventHandler((event) => { const { defaultLocale } = useRuntimeConfig().public.comvi; return { greeting: `Default locale is ${defaultLocale}` };});Shape:
interface NuxtI18nRuntimeConfig { comvi: { locales: string[]; localeObjects: Record<string, LocaleObject>; defaultLocale: string; localePrefix: 'always' | 'as-needed' | 'never'; cookieName: string; cdnUrl?: string; apiBaseUrl?: string; defaultNs: string; fallbackLanguage: string | string[]; basicHtmlTags?: string[]; detectBrowserLanguage: DetectBrowserLanguageOptions | false; };}Core APIs
Section titled “Core APIs”@comvi/nuxt builds on @comvi/core and @comvi/vue. Use the Nuxt auto-imported composables/components documented above for application code, and import lower-level core APIs from @comvi/core directly when needed.