Dynamically switching languages on the front end - a best practice guide
Complete example
Example 1: Complete Express application
Example 2: Vue 3 front end
FAQ
Q1: Why can’t I use Locale.setLocale() directly?
A: Because Node.js is single-threaded and asynchronous, multiple requests may modify the global state at the same time, causing language confusion.
Q2: Will creating a Validator instance for each request affect performance?
A: The instance creation itself is very lightweight, but it is still recommended to reuse the same Validator instance**. The reason is not that the constructor is slow, but that the compilation cache is hung on the instance; if every request is new Validator(), the same Schema will repeatedly have first compilation misses.
Q3: How to support more languages?
A: Use Locale.addLocale() to add a custom language pack.
Q4: How to cache language packs on the front end?
A: The error message returned by the backend is already localized and does not need to be processed by the frontend. If front-end validation is required:
Q5: How to handle language in Cookie or Session?
Summarize
✅ Recommended practices
- Reuse Shared Validator Instance: Incoming language via
validate(..., { locale }) - Pass language via request header: Compliant with HTTP standards
- Use middleware for unified processing: Improve code reusability
Related Documents:
Corresponding sample file
Example entry: frontend-i18n-guide.ts Description: Covers common front-end language priority parsing, form submission validation, and organizing error arrays into field-level error mapping.