If you use Laravel on the backend and React on the frontend, you probably keep your translations in lang/ and would rather not maintain the same strings twice. The vite-plugin-laravel-translations package solves the first half of that problem. It exposes your PHP translation files as a global object, and then you hit the second half: the placeholders don't match.
Laravel writes :name, i18next expects {{ name }}, and no setting in the i18next configuration translates one into the other.
To be brutally honest, this is not a revolutionary project. It is a single JavaScript file with zero runtime dependencies, and it exists because I was tired of a problem that looked like it should take five minutes to fix. It took a bit longer than that, because the details of placeholder syntax are full of traps. Here is how it works, the two challenges that mattered most, and how to use it.
The Problem
The plugin makes the translations available as window.LARAVEL_TRANSLATIONS, a nested object of strings. That object can go straight into i18next as resources:
i18n
.use(initReactI18next)
.init({
interpolation: { escapeValue: false },
resources: window.LARAVEL_TRANSLATIONS
})
Everything loads, and then a placeholder shows up on the screen as raw text:
Laravel: "Welcome back, :name"
i18next: "Welcome back, {{ name }}"
i18next lets you configure its interpolation delimiters, but there is no documented way to support Laravel's colon syntax. So the fix has to happen on the data itself.
Architecture: Keeping it Simple
The core idea is small:
- Walk: the translation tree is traversed recursively. Objects and arrays are visited, and every other value is left alone unless it is a string.
-
Rewrite: each string goes through one regular expression that turns
:nameinto{{ name }}. -
Return: by default you get a new object, and
window.LARAVEL_TRANSLATIONSstays untouched. - Register: two i18next formatters handle Laravel's casing variants.
The result is a plain object that i18next can consume directly.
Tech Stack
- Language: plain JavaScript as ES modules, so it runs in the browser, Node and bundlers without a build step.
- Dependencies: none at runtime. I wanted it to be easy to audit in one sitting.
-
Tests: Node's built-in test runner (
node:test), so there is no extra framework to install. - Target: i18next, through its formatter service for the casing variants.
-
Types:
index.d.tsships with the package and is checked withnpm run typecheck. - CI: GitHub Actions runs the suite on Node 20, 22 and 24.
Two Technical Challenges I Solved
1. Matching Placeholders Without Breaking Everything Else
A naive pattern such as /:(\w+)/g works on the happy path, but it also turns a time string like Opens at 10:30 into Opens at 10{{ 30 }}. Anything that contains a colon needs a more careful match.
The final pattern is more careful:
const LARAVEL_PLACEHOLDER = /(^|[^\w:{]):([a-zA-Z_]\w*(?:[.-]\w+)*)/g
Each part has a job:
- The name must start with a letter or underscore, so
:30is never a placeholder. - The character before the colon is captured as a group instead of being checked with a lookbehind. A colon attached to a word character, another colon or an opening brace is skipped, which keeps
10:30,mailto:x,Note:xand{{:x}}intact. The lookbehind was dropped because Safari before 16.4 cannot parse it. - The name may contain dots and dashes, which covers keys like
:user.nameand:user-name.
The test suite covers these cases on purpose, including names followed by a full stop: :min. becomes {{ min }}..
2. Laravel's Casing Variants
Laravel has a feature that is easy to forget. :name inserts the value as it is, :Name capitalises it and :NAME uppercases it. i18next has no equivalent, so the library maps each variant to a formatter:
const toPlaceholder = (name) => {
const lower = name.toLowerCase();
if (name === lower) return `{{ ${name} }}`;
if (name === name.toUpperCase()) return `{{ ${lower}, uppercase }}`;
if (name[0] === name[0].toUpperCase() && name.slice(1) === lower.slice(1)) {
return `{{ ${lower}, capitalize }}`;
}
return `{{ ${name} }}`;
};
Registering the two formatters once makes the mapping work:
import { registerFormatters } from 'laravel-translations-i18next-ffixer'
registerFormatters(i18n)
Designing for Safety
A translation tree is data, and data can be strange. Three decisions came from that:
-
Clone by default. Mutating
window.LARAVEL_TRANSLATIONSin place surprises whoever reads it next. Mutation is still available withclone: false, but it is opt-in. -
Cycles fail loudly. If an object references one of its own ancestors, the library throws a clear
TypeErrorinstead of recursing until the stack overflows. -
Keys are own properties. A key named
__proto__, which can come fromJSON.parse, would hit the prototype setter with a plain assignment. The code defines the key withObject.defineProperty, and a test keeps it that way.
Options
Everything has a sensible default, so the simplest call is ffixer(window.LARAVEL_TRANSLATIONS). When you need more control, pass an options object:
ffixer(window.LARAVEL_TRANSLATIONS, {
only: ['name'], // convert just :name and leave the other placeholders alone
spacing: false, // write {{name}} instead of {{ name }}
prefix: '[[', // custom delimiters
suffix: ']]',
})
except does the opposite of only, which is handy for names that collide with emoji shortcodes such as :smile:.
For a single string, fixString accepts the same options:
fixString('Hello :name', { spacing: false }) // 'Hello {{name}}'
Two more options matter for real projects:
-
debug: truelogs a single summary line with the number of placeholders converted, the number of strings scanned and the duration. It is a deliberately simple measurement, since running a regular expression over every string has a cost. -
plurals: truesplits Laravel plural strings such as'one apple|many apples'into_oneand_otherkeys, which is the shape i18next expects. Explicit segments such as{0}and[1,*]are mapped too. Ranges such as[2,5]are not.
Getting Started & Testing Locally
Install the package and wrap the resources in your i18next configuration:
npm install laravel-translations-i18next-ffixer
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import ffixer, { registerFormatters } from 'laravel-translations-i18next-ffixer'
i18n
.use(initReactI18next)
.init({
interpolation: { escapeValue: false },
resources: ffixer(window.LARAVEL_TRANSLATIONS)
})
registerFormatters(i18n)
export default i18n
To run the test suite from a clone of the repository:
npm test
The tests cover placeholders, nested structures, cloning versus in-place mutation, the edge cases above, options, plurals and idempotency: running the fixer twice must give the same result as running it once.
Two more scripts are available: npm run typecheck checks the TypeScript declarations, and npm run coverage reports test coverage.
What's Next?
The library does one job, and I'd like to keep it that way. A few things I'm considering:
- Deciding whether
pluralsshould become a default once it has been used in more projects. - Releasing 0.1.0. The changelog still lists it as unreleased, with two breaking changes: the package now declares an
exportsmap, so deep imports such aslaravel-translations-i18next-ffixer/src/ffixer.jsno longer work, and the positionalffixer(t, debug, clone)form prints a warning in favour of the options object. - Finding a cleaner long-term fix. The ideal solution would live in i18next or in the Vite plugin, so nobody needs a fixer at all.
If you use Laravel and React together and have hit this issue, I would love to hear how you solved it. Issues, pull requests and edge cases from real translation files are very welcome.
- Repository: github.com/devrfc83/laravel-translations-i18next-ffixer
- npm: laravel-translations-i18next-ffixer
About the Author
Hi! I'm Rodrigo Fuentealba Cartes, an entrepreneur, Bachelor of Engineering Sciences and Computer and Informatics Engineer. For more than two decades I've combined data analysis with software engineering to take projects from idea to production. Now I offer my services through a small company named Sea Dragon.
I'm also a chess player, musician, motorcyclist, amateur radio operator (license CA5NFS), and a low performance athlete.
You can find me around the web:
- Website: devrfc83.com
- GitHub: @devrfc83
- Instagram: @devrfc83
Top comments (0)