Skip to Content

i18n

Internationalization plugin for translating error messages

The i18n plugin allows you to translate error messages returned by Entro Auth based on the user's locale. It supports multiple locale detection strategies including HTTP headers, cookies, session data, and custom callbacks.

Entro Auth already provides English error messages by default, so you only need to provide translations for other languages.

Installation

Install the plugin

npm install @entro314labs/entro-auth-i18n

Add the plugin to your auth config

auth.ts
import { entroAuth } from "@entro314labs/entro-auth"
import { i18n } from "@entro314labs/entro-auth-i18n"

export const auth = entroAuth({
    plugins: [
        i18n({
            translations: {
                fr: {
                    USER_NOT_FOUND: "Utilisateur non trouvé",
                    INVALID_EMAIL_OR_PASSWORD: "Email ou mot de passe invalide",
                    INVALID_PASSWORD: "Mot de passe invalide",
                },
                de: {
                    USER_NOT_FOUND: "Benutzer nicht gefunden",
                    INVALID_EMAIL_OR_PASSWORD: "Ungültige E-Mail oder Passwort",
                    INVALID_PASSWORD: "Ungültiges Passwort",
                },
            },
        }),
    ],
})

Built-in Translations

The package ships with ready-to-use translations for 23 languages, so you don't need to write translations from scratch. Import locales from @entro314labs/entro-auth-i18n to use them.

They cover every code the core and these plugins declare: the ones in the main package (two-factor, email OTP, organization, admin, phone number, username, waitlist, anonymous, multi-session, generic OAuth, device authorization, captcha, OAuth popup, Have I Been Pwned), and the passkey, API key and CIBA plugins. That is 321 messages a language, with the SSO codes below. The translations were not reviewed by native speakers; override any message you would word differently.

Two kinds of error stay in English:

  • OAuth error responses, on purpose: the error and error_description of the OAuth provider and of anything that speaks OAuth to a client. Client software reads them, and RFC 6749 keeps error_description to ASCII.
  • Many errors of the SSO plugin. The packs hold its seven single-logout codes (SAML_ERROR_CODES) and the codes a person using your application reads (SSO_ERROR_CODES): the ones answered as JSON when a provider is registered, changed or read, a domain is verified and a sign-in is started (DOMAIN_VERIFIED, SSO_PROVIDER_NOT_FOUND, SSO_PROVIDER_ACCESS_DENIED and the like), and the ones a callback sends on to your page as error=<code> (MISSING_USER_INFO, SSO_PROFILE_MAPPING_FAILED, SSO_USER_RESOLUTION_FAILED, SSO_PROVIDER_CHANGED). The plugin does not translate a redirect, so for those your page looks the message up itself: locales[locale][code]. A translated message is the general one for its code: the English message of a few of them says more, such as the domain that could not be verified. Not in the packs: the codes that name an option of the plugin or a field of the request (OIDC_CLIENT_SECRET_REQUIRED, SAML_SIGNING_KEY_MISSING), which the developer reads, and the ones of a rejected SAML response, which answer the identity provider or arrive as error=invalid_saml_response.
CodeLanguage
arArabic
bnBengali
deGerman
elGreek
enEnglish
esSpanish
faPersian (Farsi)
frFrench
hiHindi
idIndonesian
itItalian
jaJapanese
koKorean
nlDutch
plPolish
ptPortuguese
ruRussian
svSwedish
thThai
trTurkish
ukUkrainian
viVietnamese
zhChinese (Simplified)

Use all built-in locales

auth.ts
import { entroAuth } from "@entro314labs/entro-auth"
import { i18n, locales } from "@entro314labs/entro-auth-i18n"

export const auth = entroAuth({
    plugins: [
        i18n({ translations: locales }),
    ],
})

Use a subset of locales

To keep your bundle lean, you can import only the locales you need:

auth.ts
import { entroAuth } from "@entro314labs/entro-auth"
import { i18n, locales } from "@entro314labs/entro-auth-i18n"

export const auth = entroAuth({
    plugins: [
        i18n({
            translations: {
                en: locales.en,
                fr: locales.fr,
            },
        }),
    ],
})

Override specific messages

You can spread a built-in locale and override only the messages you want to customize:

auth.ts
import { entroAuth } from "@entro314labs/entro-auth"
import { i18n, locales } from "@entro314labs/entro-auth-i18n"

export const auth = entroAuth({
    plugins: [
        i18n({
            translations: {
                ...locales,
                fr: {
                    ...locales.fr,
                    USER_NOT_FOUND: "Membre introuvable",
                },
            },
        }),
    ],
})

Add a custom locale

You can mix built-in locales with your own custom ones:

auth.ts
import { entroAuth } from "@entro314labs/entro-auth"
import { i18n, locales } from "@entro314labs/entro-auth-i18n"
import type { TranslationDictionary } from "@entro314labs/entro-auth-i18n"

const myLocale: TranslationDictionary = {
    USER_NOT_FOUND: "...",
    INVALID_EMAIL_OR_PASSWORD: "...",
    // ... other error codes
}

export const auth = entroAuth({
    plugins: [
        i18n({
            translations: {
                ...locales,
                xx: myLocale,
            },
        }),
    ],
})

Usage

The plugin automatically detects the user's locale and translates error messages accordingly. When an error is returned, the response will include both the translated message and the original message.

Error Response Format

When an error occurs and a translation is available, the response will look like this:

{
    "code": "INVALID_EMAIL_OR_PASSWORD",
    "message": "Email ou mot de passe invalide",
    "originalMessage": "Invalid email or password"
}

Locale Detection

By default, the plugin detects the locale from the Accept-Language HTTP header. You can configure multiple detection strategies that are checked in order:

auth.ts
i18n({
    translations: { /* ... */ },
    detection: ["cookie", "header", "session"], // Priority order
})

Available detection strategies:

  • header - Uses the Accept-Language HTTP header (default)
  • cookie - Reads locale from a cookie
  • session - Reads locale from the authenticated user's stored preference
  • callback - Uses a custom function to determine locale

Header-Based Detection

The plugin automatically parses the Accept-Language header, including quality values:

Accept-Language: fr-CA, fr;q=0.9, en;q=0.8

This would first try fr-CA, then fr, then en.

Tags with a Region

Every strategy matches a language tag the same way: the tag itself when you have a dictionary under that key (pt-BR), otherwise its language (fr-CA, or fr_CA, uses fr). A cookie or a profile field that holds el-GR therefore picks the el dictionary. When neither is known, the next strategy is tried.

To use cookie-based detection, add "cookie" to the detection strategies and optionally configure the cookie name:

auth.ts
i18n({
    translations: { /* ... */ },
    detection: ["cookie", "header"],
    localeCookie: "lang", // Default is "locale"
})

Session-Based Detection

If you store the user's locale preference in their profile, you can detect it from the session:

auth.ts
export const auth = entroAuth({
    user: {
        additionalFields: {
            locale: { type: "string", required: false },
        },
    },
    plugins: [
        i18n({
            translations: { /* ... */ },
            detection: ["session", "header"],
            userLocaleField: "locale", // Default is "locale"
        }),
    ],
})

Custom Detection Callback

For advanced use cases, you can provide a custom locale detection function:

auth.ts
i18n({
    translations: { /* ... */ },
    detection: ["callback", "header"],
    getLocale: (ctx) => {
        // Custom logic: use query param, custom header, etc.
        if (!ctx.request) return null;
        const url = new URL(ctx.request.url);
        return url.searchParams.get("lang");
    },
})

The callback receives the full endpoint context. It should return the locale code or null.

The Language of the Page

A browser's Accept-Language is the browser's setting, which is often not the language the person chose on your site. Give the client plugin the page's language and it goes with every request as Accept-Language, where the default "header" strategy reads it:

auth-client.ts
import { createAuthClient } from "@entro314labs/entro-auth/client";
import { i18nClient } from "@entro314labs/entro-auth-i18n/client";

export const authClient = createAuthClient({
    plugins: [
        i18nClient({ locale: () => document.documentElement.lang }),
    ],
});

locale is a tag or a function that returns the current one. A function that returns nothing leaves the browser's header as it is. Strategies listed before "header" in detection still win.

The Locale in Mail

Mail is sent from callbacks of your own, and it should be in the language the errors were in. currentLocale() returns the locale the plugin resolved for the request being handled, by the same strategies:

auth.ts
import { currentLocale, i18n } from "@entro314labs/entro-auth-i18n";

export const auth = entroAuth({
    plugins: [
        i18n({ translations: { /* ... */ } }),
        emailOTP({
            async sendVerificationOTP({ email, otp }) {
                await sendCode(email, otp, await currentLocale());
            },
        }),
    ],
});

It works in any callback the library runs while it handles a request, whatever that callback is handed. Outside a request it throws.

Error Codes

The plugin translates error messages based on error codes. You can find all available error codes in the Error Codes Reference.

Common error codes include:

CodeDefault Message
USER_NOT_FOUNDUser not found
INVALID_EMAIL_OR_PASSWORDInvalid email or password
INVALID_PASSWORDInvalid password
CREDENTIAL_ACCOUNT_NOT_FOUNDCredential account not found
EMAIL_NOT_VERIFIEDEmail not verified
SESSION_EXPIREDSession expired

Options

translations

Type: Record<string, Record<string, string>>

Required: Yes

A dictionary of translations keyed by locale code. Each locale contains a mapping of error codes to translated messages. Since Entro Auth already provides English messages, you typically only need to provide translations for other languages.

translations: {
    fr: { USER_NOT_FOUND: "Utilisateur non trouvé" },
    de: { USER_NOT_FOUND: "Benutzer nicht gefunden" },
}

defaultLocale

Type: string

Default: "en"

The fallback locale to use when no locale can be detected or the detected locale is not in the translations.

detection

Type: Array<"header" | "cookie" | "session" | "callback">

Default: ["header"]

An array of detection strategies to use, in priority order. The first strategy that returns a valid locale will be used.

localeCookie

Type: string

Default: "locale"

The name of the cookie to read when using the "cookie" detection strategy.

userLocaleField

Type: string

Default: "locale"

The field name on the user object that stores their locale preference when using the "session" detection strategy.

getLocale

Type: (ctx: GenericEndpointContext) => string | null | Promise<string | null>

A custom function to detect the locale when using the "callback" detection strategy. Receives the full endpoint context. Returns the locale code or null.

ctx.request could be undefined for non-HTTP calls.

Fallback Behavior

  • If a translation is not found for a specific error code in the detected locale, the built-in English message is kept.
  • If the detected locale is not in the translations dictionary, the plugin falls back to defaultLocale.
  • If no locale can be detected from any strategy, the plugin falls back to defaultLocale (defaults to "en").
  • Non-error responses are never modified by this plugin.
  • An error is translated whether the endpoint or a before hook threw it.
  • A request refused before it reaches an endpoint, by the rate limiter (TOO_MANY_REQUESTS) or the origin check, is translated too. No endpoint ran for it, so only the header and cookie strategies can say which language: session and callback are passed over, and the default locale is used when neither of the other two is configured or matches.

On this page