Skip to content

@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.

Configure the module under the comvi key in nuxt.config.ts:

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',
},
});
OptionTypeDefaultDescription
defaultLocalestringLocale 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
cdnUrlstringFull CDN URL for loading translations in production
apiKeystringAPI key for authenticated requests (dev mode). See security note below.
apiBaseUrlstringAPI base URL for loading translations
defaultNsstring'default'Default namespace for translations
fallbackLanguagestring | string[]Same as defaultLocaleLanguage(s) used when a translation key is missing
detectBrowserLanguageobject | falseSee belowBrowser language detection settings. Set to false to disable
basicHtmlTagsstring[]HTML tags allowed in tag interpolation
setupstringAuto-detectedPath to a setup file that runs before i18n.init(). Auto-detects ./comvi.setup.* in project root
PropertyTypeRequiredDescription
codestringYesBCP 47 language code (e.g., en, de, ar)
namestringNoHuman-readable name (e.g., English, Deutsch)
dir'ltr' | 'rtl'NoText direction. Defaults to 'ltr'
isostringNoISO code for SEO (e.g., en-US). Used in hreflang tags
PropertyTypeDefaultDescription
useCookiebooleantruePersist detected locale in a cookie
cookieNamestring'i18n_locale'Cookie name for the persisted locale
cookieMaxAgenumber31536000Cookie max age in seconds (default: 1 year)
cookieSecurebooleantrueSet the Secure flag outside dev mode
redirectOnFirstVisitbooleantrueRedirect to detected locale on first visit
fallbackLocalestringdefaultLocaleLocale when detection fails or returns unsupported locale
nuxt.config.ts
comvi: {
detectBrowserLanguage: {
useCookie: true,
cookieName: 'i18n_locale',
redirectOnFirstVisit: true,
fallbackLocale: 'en',
},
}

Set detectBrowserLanguage: false to disable automatic detection entirely.

ModeDefault Locale URLOther Locale URLDescription
as-needed/about/de/aboutDefault locale has no URL prefix
always/en/about/de/aboutAll locales get a prefix
never/about/aboutNo URL prefixes; locale set via cookie or header

All composables are auto-imported by the module. You never need import statements for them.

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>
useI18n(ns?: string)

Pass an optional namespace string to scope all t() calls to that namespace.

Reactive state:

PropertyTypeDescription
t(key: string, params?) => stringTranslate a key with optional interpolation parameters
tRaw(key: string, params?) => TranslationResultReturn structured output for advanced renderers
localeRef<string>Current language (reactive, writable)
isLoadingReadonly<Ref<boolean>>true while translations are being fetched
isInitializingReadonly<Ref<boolean>>true during init()
translationCacheReadonly<Ref<Readonly<ReadonlyMap<string, FlattenedTranslations>>>>Translation cache (reactive)
dirComputedRef<"ltr" | "rtl">Text direction for the current locale. Useful for RTL layout
loadedLocalesComputedRef<string[]>Reactive list of all loaded locale codes
activeNamespacesComputedRef<string[]>Reactive list of active namespaces
defaultNamespaceComputedRef<string>Reactive default namespace

Nuxt-specific:

PropertyTypeDescription
localesRef<readonly string[]>Configured locale list from module options (read .value in script)
defaultLocaleRef<string>Configured default locale (read .value in script)

Methods:

MethodTypeDescription
setLocale(lang: string) => Promise<void>Switch language and wait for translations to load
addTranslations(translations: Record<string, Record<string, TranslationValue>>) => voidAdd translations at runtime
addActiveNamespace(ns: string) => Promise<void>Load a new namespace dynamically
setFallbackLocale(locales: string | string[]) => voidConfigure fallback locale chain
onMissingKey(cb: (key, locale, namespace) => TranslationResult | void) => () => voidRegister callback for missing keys (returns unsubscribe)
onLoadError(cb: (locale, namespace, error) => void) => () => voidRegister callback for load errors (returns unsubscribe)
clearTranslations(locale?, namespace?) => voidClear 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?) => booleanImperative (non-reactive) locale check — plain boolean, safe in event handlers, loops, or outside a reactive scope.
hasTranslationNow(key, opts?: { locale?, namespace?, checkFallbacks? }) => booleanImperative (non-reactive) translation-existence check — plain boolean, safe outside a reactive scope.
on(event, callback) => () => voidSubscribe to i18n events (returns unsubscribe)
reportError(error, context?) => voidReport an error to the configured handler
formatNumber(value, opts?) => stringFormat a number using the current locale
formatDate(value, opts?) => stringFormat a date using the current locale
formatCurrency(value, currency, opts?) => stringFormat a number as currency
formatRelativeTime(value, unit, opts?) => stringFormat a relative time (“2 hours ago”, “in 3 days”)

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>
const localePath: (path: RouteLocationRaw, locale?: string) => string;
ArgumentTypeDefaultDescription
pathRouteLocationRawThe path or route object to prefix (required)
localestringCurrent localeOverride the locale for the generated path

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>
const switchLocalePath: (locale: string) => string;

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>
const localeRoute: (path: RouteLocationRaw, locale?: string) => RouteLocationResolved | undefined;

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>
PropertyTypeDefaultDescription
baseUrlstringAuto-detectedBase URL for canonical and alternate links
addOgLocalebooleantrueAdd og:locale and og:locale:alternate meta tags
addAlternateLinksbooleantrueAdd hreflang alternate link tags
addCanonicalbooleantrueAdd a canonical <link> tag
addDirbooleantrueSet the dir attribute on <html> (requires dir on locale object)
addLangbooleantrueSet the lang attribute on <html>

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();
PropertyTypeDescription
localesreadonly string[]Configured locale codes
defaultLocalestringConfigured default locale
localePrefix'always' | 'as-needed' | 'never'URL prefix mode
getPathname({ locale, href }) => stringBuild a localized pathname
getAllLocalizedPaths(href: string) => Array<{ locale, path }>All localized versions of a path
server/routes/sitemap.xml.ts
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 })}`,
}))
);
});

The module auto-imports server utilities into server/ handlers:

UtilitySignatureDescription
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?) => RuntimeConfigRead public/private Comvi runtime config on the server
server/api/hello.ts
export default defineEventHandler(async (event) => {
const { t, locale } = await useTranslation(event);
return {
message: t('api.hello'),
locale,
};
});

Auto-imported. Renders translations with rich content safely using named slots. Same behavior as the @comvi/vue <T> component.

PropTypeDefaultDescription
i18nKeystringTranslation key to resolve (required)
paramsRecord<string, unknown>{}Interpolation parameters
nsstringNamespace to look up the key in
localestringSpecific locale to use
fallbackstringFallback text if the key is missing
rawbooleanWhen true, prevents post-processors (such as the in-context editor marker injector) from adding invisible marker characters
componentsRecord<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>

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:

PropTypeDefaultDescription
tostring | RouteLocationRawTarget path (will be locale-prefixed, required)
localestringCurrent localeOverride the locale for the link’s to path

Available in all templates without calling useI18n(). Translates a key with optional parameters.

components/Footer.vue
<template>
<footer>
<p>{{ $t('footer.copyright', { year: 2025 }) }}</p>
</footer>
</template>

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:

comvi.setup.ts
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:

PropertyTypeDescription
i18nVueI18n | I18nThe i18n instance for this runtime (Vue in plugin, core I18n in server utils)
runtime'client' | 'server'Where the hook is executing
nuxtAppNuxtApp?Available in the runtime plugin
eventH3Event?Available in server utilities
runtimeConfigRuntimeConfig?Public + private Nuxt runtime config

Runs before i18n.init() for both the client plugin and server utility instances.

Access module config via useRuntimeConfig().public.comvi:

server/api/greeting.ts
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;
};
}

@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.