Ask your question and get a summary of the document by referencing this page and the AI provider of your choice
Version History
- "Init history"v5.5.106/29/2025
If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentationCopy doc Markdown to clipboard
Documentation: t Function in express-intlayer
The t function in the express-intlayer package is the core utility for providing localized responses in your Express application. It simplifies internationalization (i18n) by dynamically selecting content based on the user's preferred language.
Overview
The t function is used to define and retrieve translations for a given set of languages. It automatically determines the appropriate language to return based on the client's request settings, such as the Accept-Language header. If the preferred language is unavailable, it gracefully falls back to the default locale specified in your configuration.
Key Features
- Dynamic Localization: Automatically selects the most appropriate translation for the client.
- Fallback to Default Locale: Falls back to a default locale if the client's preferred language isn't available, ensuring continuity in user experience.
- Lightweight and Fast: Designed for high-performance applications, ensuring minimal overhead.
- Strict Mode Support: Enforce strict adherence to declared locales for reliable behavior.
Function Signature
Parameters
translations: An object where the keys are locale codes (e.g.,en,fr,es-MX) and the values are the corresponding translated strings.
Returns
- A string representing the content in the client's preferred language.
Loading the Internationalization Request Handler
To ensure that the internationalization functionality provided by express-intlayer works correctly, you must load the internationalization middleware at the beginning of your Express application. This enables the t function and ensures proper handling of locale detection and translation.
Place the app.use(intlayer()) middleware before any routes in your application to ensure that all routes benefit from internationalization:
Why This is Required
- Locale Detection: The
intlayermiddleware processes incoming requests to detect the user's preferred locale based on headers, cookies, or other configured methods. - Translation Context: Sets up the necessary context for the
tfunction to operate correctly, ensuring that translations are returned in the correct language. - Error Prevention: Without this middleware, using the
tfunction will result in runtime errors because the necessary locale information won't be available.
Usage Examples
Basic Example
Serve localized content in different languages:
Client Requests:
- A client with
Accept-Language: frwill receiveBienvenue!. - A client with
Accept-Language: eswill receive¡Bienvenido!. - A client with
Accept-Language: dewill receiveWelcome!(default locale).
Handling Errors
Provide error messages in multiple languages:
Using Locale Variants
Specify translations for locale-specific variants:
Advanced Topics
Fallback Mechanism
If a preferred locale is unavailable, the t function will fallback to the default locale defined in the configuration:
For example:
- If
defaultLocaleisLocales.CHINESEand a client requestsLocales.DUTCH, the returned translation will default to theLocales.CHINESEvalue. - If
defaultLocaleis not defined, thetfunction will fallback to theLocales.ENGLISHvalue.
Strict Mode Enforcement
Configure the t function to enforce strict adherence to declared locales:
Open the table in a modal to view all data content clearly
| Mode | Behavior |
|---|---|
strict | All declared locales must have translations provided. Missing locales will throw errors. |
inclusive | Declared locales must have translations. Missing locales trigger warnings but are accepted. |
loose | Any existing locale is accepted, even if not declared. |
Configuration Example:
TypeScript Integration
The t function is type-safe when used with TypeScript. Define a type-safe translations object:
Common Errors and Troubleshooting
Open the table in a modal to view all data content clearly
| Issue | Cause | Solution |
|---|---|---|
t function not working | Middleware not loaded | Ensure app.use(intlayer()) is added before routes. |
| Missing translations error | Strict mode enabled without all locales | Provide all required translations. |
Tips for Effective Usage
- Centralize Translations: Use a centralized module or JSON files for managing translations to improve maintainability.
- Validate Translations: Ensure every language variant has a corresponding translation to prevent falling back unnecessarily.
- Combine with Frontend i18n: Synchronize with frontend internationalization for a seamless user experience across the app.
- Benchmark Performance: Test your app's response times when adding translations to ensure minimal impact.
Conclusion
The t function is a powerful tool for backend internationalization. By using it effectively, you can create a more inclusive and user-friendly application for a global audience. For advanced usage and detailed configuration options, refer to the documentation.