Composables

useTranslation

Description

The useTranslation composable provides a wrapper around the Nuxt i18n translation function, with enhanced support for debugging translation keys and optional fallback strings. It conditionally displays raw translation keys based on a query parameter, making it useful for localization audits and development environments.

FEATURE GOALS

  • Provide a consistent and customizable way to handle translations.
  • Allow display of raw translation keys via URL query for debugging.
  • Suppress non-critical i18n warnings to reduce console noise.

FEATURE EXPECTATIONS

  • Returns the translated string using Nuxt’s $i18n.t() method.
  • Displays the key itself if showTranlsationKeys=true is present in the URL query.
  • Suppresses translation warnings (e.g., missing, fallback, silent).

DEV STRATEGIES

  1. Composables Logic
const greeting = useTranslation('home.welcome', 'Welcome!');
  • Returns a translated message or a fallback if missing.
  • If ?showTranlsationKeys=true is present in the URL, it will return "home.welcome" directly.
  1. Implementation
export const useTranslation = (key: string, default_string?: string) => {
  const nuxtApp = useNuxtApp();
  const route = useRoute();
  if (route && route.query && route.query.showTranlsationKeys === 'true') {
    return key;
  }

  return nuxtApp.$i18n.t(key, default_string, {
    missingWarn: false,
    silentTranslationWarn: true,
    fallbackWarn: false,
  });
};
  • Integrates with Nuxt app context and current route.
  • Provides translation with suppressible warnings.
  1. DEFAULT BEHAVIOR
FeatureDefaultDescription
keyrequiredTranslation key from i18n resources.
default_stringoptionalFallback string if translation is missing.
showTranlsationKeysfalseIf query param is true, returns the raw key instead of the translation.
missingWarnfalseDisables warning for missing translation keys..
silentTranslationWarntrueSilences translation warnings entirely.
fallbackWarnfalseSuppresses fallback-related warnings.

FLOW SUMMARY

  • Reads the route query to determine whether to show translation keys.
  • If showTranlsationKeys=true, returns the raw key to aid in debugging.
  • Otherwise, returns the translated string (or a fallback) via $i18n.t().
  • Suppresses i18n-related warnings for cleaner developer experience.

Copyright © 2026