DEV Community

Rodrigo Fuentealba Cartes
Rodrigo Fuentealba Cartes

Posted on Edited on AI-assisted

I wrote a library that allows me to use Laravel translations in React with i18next

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
  })
Enter fullscreen mode Exit fullscreen mode

Everything loads, and then a placeholder shows up on the screen as raw text:

Laravel:  "Welcome back, :name"
i18next:  "Welcome back, {{ name }}"
Enter fullscreen mode Exit fullscreen mode

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 :name into {{ name }}.
  • Return: by default you get a new object, and window.LARAVEL_TRANSLATIONS stays 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.ts ships with the package and is checked with npm 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
Enter fullscreen mode Exit fullscreen mode

Each part has a job:

  • The name must start with a letter or underscore, so :30 is 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:x and {{: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.name and :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} }}`;
};
Enter fullscreen mode Exit fullscreen mode

Registering the two formatters once makes the mapping work:

import { registerFormatters } from 'laravel-translations-i18next-ffixer'

registerFormatters(i18n)
Enter fullscreen mode Exit fullscreen mode

Designing for Safety

A translation tree is data, and data can be strange. Three decisions came from that:

  • Clone by default. Mutating window.LARAVEL_TRANSLATIONS in place surprises whoever reads it next. Mutation is still available with clone: false, but it is opt-in.
  • Cycles fail loudly. If an object references one of its own ancestors, the library throws a clear TypeError instead of recursing until the stack overflows.
  • Keys are own properties. A key named __proto__, which can come from JSON.parse, would hit the prototype setter with a plain assignment. The code defines the key with Object.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: ']]',
})
Enter fullscreen mode Exit fullscreen mode

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}}'
Enter fullscreen mode Exit fullscreen mode

Two more options matter for real projects:

  • debug: true logs 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: true splits Laravel plural strings such as 'one apple|many apples' into _one and _other keys, 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
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

To run the test suite from a clone of the repository:

npm test
Enter fullscreen mode Exit fullscreen mode

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 plurals should 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 exports map, so deep imports such as laravel-translations-i18next-ffixer/src/ffixer.js no longer work, and the positional ffixer(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.


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:

Top comments (0)