Skip to content

add i18n support - #6796

Open
benedikt-bartscher wants to merge 191 commits into
reflex-dev:mainfrom
benedikt-bartscher:add-i18n
Open

benedikt-bartscher wants to merge 191 commits into
reflex-dev:mainfrom
benedikt-bartscher:add-i18n

Conversation

@benedikt-bartscher

@benedikt-bartscher benedikt-bartscher commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

closes #2339

@codspeed

codspeed Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 16 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 146 untouched benchmarks
⏩ 8 skipped benchmarks1


Comparing benedikt-bartscher:add-i18n (94e2dd7) with main (8e0e881)

Open in CodSpeed

Footnotes

  1. 8 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@greptile-apps

greptile-apps Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5RetriggerView in Greptile

[High impact] This PR is safe to merge with minimal risk

Findings

  1. P2 Default pages omit translations ▶

Summary

This PR adds comprehensive internationalization (i18n) support to Reflex through a new reflex-i18n package. The implementation includes:

  • Translation API: rx.t() for static content and gettext()/ngettext()/pgettext() for server-side dynamic translation
  • Locale routing: Two modes — path prefix (/de/pricing) or cookie-based single URL
  • Client runtime: JavaScript runtime in _web/i18n.js handling locale switching, catalog loading, and formatting
  • Build-time extraction: CLI commands (reflex i18n extract, init, translate) for managing .po catalogs
  • Formatting helpers: Locale-aware date, number, and currency formatting via browser Intl API
  • Plugin architecture: Event scope providers for per-request locale context, implicit dependency tracking for computed var reactivity

The implementation touches core framework areas:

  • Event processing gains an ambient scope system (locale, potentially others)
  • Computed var dependency scanner now tracks implicit dependencies from function calls
  • Plugin system adds two-pass route expansion and page evaluation scopes
  • State reload logic purges dangling dependency edges

Reviews (102) · Last reviewed commit: "docs(i18n): without URL routing a page f..." · Reviewed by Greptile

Comment thread reflex/__init__.py Resolved
@benedikt-bartscher
benedikt-bartscher marked this pull request as ready for review July 18, 2026 11:09
@benedikt-bartscher
benedikt-bartscher requested review from a team and Alek99 as code owners July 18, 2026 11:09
@benedikt-bartscher benedikt-bartscher changed the title first i18n wip add basic i18n support Jul 18, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6b9a5f5342

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread packages/reflex-i18n/pyproject.toml Resolved
Comment thread reflex/reflex.py Resolved
@benedikt-bartscher benedikt-bartscher changed the title add basic i18n support add i18n support Jul 18, 2026
@benedikt-bartscher

Copy link
Copy Markdown
Contributor Author

@masenf could you please take a brief look at this from an architectural design and DX perspective? it's totally okay if you have smth completly different in mind

@masenf masenf left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@benedikt-bartscher thanks for adding this and sorry for the review back-up. i did an initial look and i think the added extension points make sense and the API feels nice.

one potential issue i see affects SEO performance of the SSG static versions of the site -- since the translation depends on state, other languages might not be indexable by crawlers.

… its validated config, no top-level rx.I18nConfig
@FarhanAliRaza FarhanAliRaza added the priority: P2 Medium: valid edge-case bug, reasonable feature, or docs fix label Nov 30, 2026 — with Claude
… and trailing slashes, get_config and get_plugin imported at module top
…arse, through catalog.py's reader, and counts with is_translated
…odule top, one helper resolves a delta in it
…switches a URL-routed locale through useUrlLocaleSetter
…parsable tag up front instead of retrying mid-file
…d page_alternates, I18nPlugin imported at nav's top
…hook helpers, the registry fixture resets to no config

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 43 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="docs/i18n/overview.md">

<violation number="1" location="docs/i18n/overview.md:221">
P2: This test asserts a German message without creating or referencing a `locales/de.po` catalog containing `Report for {month}`. Add a catalog fixture before activating the config, or change the expected value to the untranslated source message; otherwise the example fails in a fresh test project.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

Comment thread docs/i18n/overview.md
def test_report_title_in_german():
with active_i18n_config(I18nConfig(locales=["en", "de"])):
title = monthly_report_title("de", datetime.date(2026, 1, 31))
assert title == "Bericht für 31.01.2026"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This test asserts a German message without creating or referencing a locales/de.po catalog containing Report for {month}. Add a catalog fixture before activating the config, or change the expected value to the untranslated source message; otherwise the example fails in a fresh test project.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/i18n/overview.md, line 221:

<comment>This test asserts a German message without creating or referencing a `locales/de.po` catalog containing `Report for {month}`. Add a catalog fixture before activating the config, or change the expected value to the untranslated source message; otherwise the example fails in a fresh test project.</comment>

<file context>
@@ -207,6 +207,20 @@ def monthly_report_title(user_locale: str, month: datetime.date) -> str:
+def test_report_title_in_german():
+    with active_i18n_config(I18nConfig(locales=["en", "de"])):
+        title = monthly_report_title("de", datetime.date(2026, 1, 31))
+    assert title == "Bericht für 31.01.2026"
+```
+
</file context>

…configured machine translation provider

I18nPlugin(machine_translation=...) takes any MachineTranslationProvider
(async translate(texts, *, source, target)); PrefixTranslationProvider is a
stand-in for tests and demos. Drafts are flagged fuzzy, fuzzy and read-only
entries stay as they are, a draft that changes a placeholder is left out, and
every locale is drafted in one event loop so a provider may keep its client.
check lists the missing and fuzzy messages, and extract keeps a .po header's
creation date so only messages.pot records the extraction.
# Conflicts:
#	tests/units/compiler/test_compiler.py

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 9 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="docs/i18n/overview.md">

<violation number="1" location="docs/i18n/overview.md:661">
P3: This provider example references the undefined `my_service`, so copying the documented configuration fails when translation runs. Make the example self-contained or show how the service is injected/imported.</violation>
</file>

<file name="packages/reflex-i18n/src/reflex_i18n/machine_translation.py">

<violation number="1" location="packages/reflex-i18n/src/reflex_i18n/machine_translation.py:16">
P2: `keeps_placeholders` accepts drafts that drop or alter formatted fields such as `{count:,}` or `{name!s}` because the regex only recognizes bare field names. Parse Python format fields (and the supported percent format syntax) so `reflex i18n translate` cannot write a draft that loses interpolation data.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

from typing import Protocol, runtime_checkable

# The runtime's {name} placeholders and gettext's %(name)s ones.
_PLACEHOLDER_RE = re.compile(r"\{\w+\}|%\(\w+\)[a-z]")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: keeps_placeholders accepts drafts that drop or alter formatted fields such as {count:,} or {name!s} because the regex only recognizes bare field names. Parse Python format fields (and the supported percent format syntax) so reflex i18n translate cannot write a draft that loses interpolation data.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/reflex-i18n/src/reflex_i18n/machine_translation.py, line 16:

<comment>`keeps_placeholders` accepts drafts that drop or alter formatted fields such as `{count:,}` or `{name!s}` because the regex only recognizes bare field names. Parse Python format fields (and the supported percent format syntax) so `reflex i18n translate` cannot write a draft that loses interpolation data.</comment>

<file context>
@@ -0,0 +1,89 @@
+from typing import Protocol, runtime_checkable
+
+# The runtime's {name} placeholders and gettext's %(name)s ones.
+_PLACEHOLDER_RE = re.compile(r"\{\w+\}|%\(\w+\)[a-z]")
+
+
</file context>

Comment thread docs/i18n/overview.md
class MyTranslationService:
async def translate(self, texts, *, source, target):
# Ask your translation service; one translation per text, in order.
return await my_service.translate(texts, source=source, target=target)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: This provider example references the undefined my_service, so copying the documented configuration fails when translation runs. Make the example self-contained or show how the service is injected/imported.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/i18n/overview.md, line 661:

<comment>This provider example references the undefined `my_service`, so copying the documented configuration fails when translation runs. Make the example self-contained or show how the service is injected/imported.</comment>

<file context>
@@ -639,7 +644,43 @@ I18nPlugin(
+class MyTranslationService:
+    async def translate(self, texts, *, source, target):
+        # Ask your translation service; one translation per text, in order.
+        return await my_service.translate(texts, source=source, target=target)
+
+
</file context>

Comment on lines +465 to +467
if localized == base_path:
# Default-at-root: the app's own page already serves this.
continue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Default pages omit translations

With URL routing and a populated default-locale catalog, this continue leaves the original page without a static catalog. I18nProvider starts without one and loads it only in useEffect, so the prerendered HTML contains source messages instead of the default catalog's translations. Search engines and visitors before the app loads see those original labels, while other locale routes receive translations immediately through LocaleRoute.

Provide the default catalog synchronously too, while preserving cookie-mode switching.

…e to the dependencies they imply

A computed var that called gettext through a module-level helper kept no
dependency on the locale, so a locale switch left its cached text in the
old language for the rest of the session. Library functions stay
unfollowed: walking them cost 40.9 ms per scan instead of 0.2 ms, and a
library registers its own functions.
…its locale prefix

The German copy of an untitled home page was titled "<App> | De".
…nnot suppress it

No provider suppressed one, so the bool returns of the proxies' __aexit__,
the early return after an event's handler and the empty delta after a
failed resolution served no caller.
… for implied dependencies

_populate_dependencies drops from 21 to 17 branches (16 on main): the
paired LOAD_FAST loads and the global, closure and module attribute loads
each go through a method of their own.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 12 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/reflex-base/src/reflex_base/vars/dep_tracking.py">

<violation number="1" location="packages/reflex-base/src/reflex_base/vars/dep_tracking.py:398">
P2: `_seen` deduplicates helpers by `__code__`, but separate closures can share that code while capturing different functions. A getter that references a non-translating closure helper before a closure around `gettext` therefore misses the locale dependency and keeps its cached translation after a locale switch; key this set by helper identity or include closure identity.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

helper: A function the getter references.
"""
code = helper.__code__
if code in self._seen:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: _seen deduplicates helpers by __code__, but separate closures can share that code while capturing different functions. A getter that references a non-translating closure helper before a closure around gettext therefore misses the locale dependency and keeps its cached translation after a locale switch; key this set by helper identity or include closure identity.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/reflex-base/src/reflex_base/vars/dep_tracking.py, line 398:

<comment>`_seen` deduplicates helpers by `__code__`, but separate closures can share that code while capturing different functions. A getter that references a non-translating closure helper before a closure around `gettext` therefore misses the locale dependency and keeps its cached translation after a locale switch; key this set by helper identity or include closure identity.</comment>

<file context>
@@ -297,6 +383,33 @@ def _add_implicit_dependency(self, obj: object) -> None:
+            helper: A function the getter references.
+        """
+        code = helper.__code__
+        if code in self._seen:
+            return
+        self._seen.add(code)
</file context>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation enhancement Anything you want improved on deck PRs lined up to review / merge next priority: P2 Medium: valid edge-case bug, reasonable feature, or docs fix roadmap https://github.com/reflex-dev/reflex/issues/2727

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Internationalization (I18N) and localization (L10N) (Feature Request)

3 participants