A guest from Osaka opens Mrs. Sri's page for the first time: no cookie, not logged in, nothing clicked yet. The very first HTML can still be in Japanese, because the browser sends along the list of languages the guest speaks, from most to least fluent, in the Accept-Language header. That's the core of server-side i18n: the server picks the language, then sends HTML, emails and API messages that are already in that language. It works like the Mist Homestay receptionist greeting a guest at the door, before the guest opens any brochure. She can look at the guest's booking card (a saved choice), or listen to the list of languages the guest speaks. From that she picks a language she speaks, and greets the guest in it from the very first word.
Accept-Language: a list of languages weighted by q
Each language in the header may carry a weight q from 0 to 1. Without q, the weight is 1. Higher means more wanted, and q=0 means "not this language". We read the header Firefox 146 really sends: with the language list Japanese, English (US), English, it's ja,en-US;q=0.7,en;q=0.3. Rina, who set Indonesian, English (US), English, Japanese, sends id,en-US;q=0.8,en;q=0.5,ja;q=0.3.
The negotiation: sort by q, then take the first language that's supported. Look for an exact match first, then for the same language (ja matches ja-JP).
function negotiate(header, supported, fallback) {
const wanted = header
.split(',')
.map((part, index) => {
const [tag, ...params] = part.trim().split(';');
const q = params.map((p) => p.trim()).find((p) => p.startsWith('q='));
return { tag: tag.trim().toLowerCase(), q: q ? Number(q.slice(2)) : 1, index };
})
.filter((w) => w.tag && w.q > 0)
.sort((a, b) => b.q - a.q || a.index - b.index);
for (const w of wanted) {
const exact = supported.find((s) => s.toLowerCase() === w.tag);
if (exact) return exact;
const sameLanguage = supported.find((s) => s.split('-')[0].toLowerCase() === w.tag.split('-')[0]);
if (sameLanguage) return sameLanguage;
}
return fallback;
}
const SUPPORTED = ['en-US', 'id-ID', 'ja-JP', 'ar-EG'];
negotiate('ja,en-US;q=0.7,en;q=0.3', SUPPORTED, 'en-US'); // 'ja-JP'
negotiate('en;q=0.5,ja', SUPPORTED, 'en-US'); // 'ja-JP': q 1 wins
negotiate('fr-FR,fr;q=0.9', SUPPORTED, 'en-US'); // 'en-US': nothing matches
If ja-JP isn't ready yet, the Osaka guest gets en-US, their second language (q 0.7). Old code often writes header.split(',')[0]: for en;q=0.5,ja that gives en, even though ja has q 1, and an unsupported language gets picked too.
Laravel uses Symfony's Request::getPreferredLanguage(). We ran it in Laravel 13.35.0 (symfony/http-foundation 8.1.8): with the list ['en-US', 'id-ID', 'ja-JP', 'ar-EG'], the Osaka header gives 'ja_JP', with an underscore. Symfony turns every locale into the language_REGION style. The Paris header (fr-FR,fr;q=0.9) gives the first item of the list, 'en_US'. With the list ['en', 'id', 'ja', 'ar'], the result is 'ja', 'ar', 'en' or 'id', matching the lang/ folder names.
The order of sources: URL, user, cookie, then the header
Accept-Language is only a guess from the browser's settings. The guest's own choice wins:
// app/Http/Middleware/SetLocale.php
class SetLocale
{
private const SUPPORTED = ['en', 'id', 'ja', 'ar'];
public function handle(Request $request, Closure $next): Response
{
$candidates = [
$request->route('locale'), // 1. URL prefix: /ja/room
$request->user()?->locale, // 2. the logged-in user
$request->cookie('lang'), // 3. cookie
$request->getPreferredLanguage(self::SUPPORTED), // 4. Accept-Language, then 'en'
];
// The first one that's there and supported wins.
App::setLocale(collect($candidates)->first(fn ($l) => in_array($l, self::SUPPORTED, true)) ?? 'en');
return $next($request);
}
}
- Register it in
bootstrap/app.php:$middleware->web(append: [SetLocale::class]);. The URL prefix comes fromRoute::prefix('{locale}')->whereIn('locale', ['en', 'id', 'ja', 'ar'])->group(...). App::setLocale()changes the locale for this request only.App::currentLocale()reads it,App::isLocale('ja')checks it.- Laravel encrypts every cookie. A
lang=jacookie written by JavaScript can't be decrypted, so$request->cookie('lang')givesnull. Exclude its name:$middleware->encryptCookies(except: ['lang']);.
Laravel: the lang folder, __() and trans_choice
The Laravel 13 skeleton has no lang folder; php artisan lang:publish creates it. One folder per locale, one file per group of texts:
// lang/ar/booking.php
return [
'room' => 'غرفة التراس',
'thanks' => 'شكرًا لكَ يا :name!',
'nights' => ':count ليلة|ليلة واحدة|ليلتان|:count ليالٍ|:count ليلة|:count ليلة',
];
App::setLocale('ar');
__('booking.room'); // "غرفة التراس"; trans('booking.room') is the same
__('booking.thanks', ['name' => 'Alex']); // "شكرًا لكَ يا Alex!"
trans_choice('booking.nights', 3); // "3 ليالٍ"
trans_choice isn't ICU. Laravel splits the text at | and picks a piece by its number, from a table of rules per locale inside Laravel. Measured in Laravel 13.35.0:
| n | ar |
en (:count night then :count nights) |
id, ja |
|---|---|---|---|
| 1 | ليلة واحدة (the 2nd piece) | 1 night (the 1st) | the 1st piece |
| 2 | ليلتان (the 3rd) | 2 nights (the 2nd) | the 1st piece |
| 3 | 3 ليالٍ (the 4th) | 3 nights | the 1st piece |
- The order of the pieces for
arfollows the CLDR categories: zero, one, two, few, many, other. In ICU the categories are written by name (two {ليلتان}), so the order doesn't matter; in Laravel the wrong order means the wrong sentence.:countis written as it is ("3"), while ICU's#is formatted for the locale ("٣"). - Explicit ranges work too:
'{0} No nights yet|{1} :count night|[2,*] :count nights'. - Laravel's locale names use underscores (
ar,ar_EG). WithApp::setLocale('ar-EG'),trans_choicealways takes the first piece: we got "1 ليلة" and "2 ليلة".
Render with the right lang and dir
A server that already knows the language writes the right <html> straight away, so nothing flashes. The Content-Language header names the language, and Vary tells caches that the page depends on the header and the cookie, so a CDN doesn't send the Japanese page to an Indonesian guest.
{{-- The response carries the headers: Content-Language: ja-JP and Vary: Accept-Language, Cookie --}}
@php($tag = ['id' => 'id-ID', 'en' => 'en-US', 'ja' => 'ja-JP', 'ar' => 'ar-EG'][app()->getLocale()])
<html lang="{{ $tag }}" dir="{{ app()->getLocale() === 'ar' ? 'rtl' : 'ltr' }}">
Hydration mismatch: the server and the browser format differently
In React or Next.js, the HTML is rendered on the server (Node) first, then React in the browser renders the same components again and compares the text. That step is called hydration. If the text differs, React throws the server's HTML away and renders again. We tested it with React 19.2.4:
| Code | Server (Node 22.22.1, UTC zone) | Browser (Chrome 147, Asia/Singapore zone) |
|---|---|---|
new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR' }).format(700000), on the page for guests from Indonesia |
"Rp 700.000" (CLDR 48: 0 decimals) | "Rp 700.000,00" |
new Intl.DateTimeFormat('en-US', { timeStyle: 'short' }).format(checkIn) |
"6:00 AM" | "2:00 PM" |
Chrome 156 already writes "Rp 700.000" like Node, but Firefox 148 still writes "Rp 700.000,00", and the hours still differ.
React writes: "Hydration failed because the server rendered text didn't match the client. As a result this tree will be regenerated on the client.", and one of the causes it lists is "Date formatting in a user's locale which doesn't match the server." In a production build the message is "Minified React error #418".
- Always write the options:
maximumFractionDigits: 0andtimeZone: 'Asia/Singapore', with the locale the server sent, notnavigator.language. - Even the same options can differ between engines: Safari 26.4 writes "Rp700.000" with no space, Node "Rp 700.000". The safest: format once on the server and send the string as props.
- PHP carries its own ICU too:
Number::currency(700000, in: 'IDR', locale: 'id')gives "Rp 700.000,00" in PHP 8.4.6 (ICU 77.1). Addprecision: 0for "Rp 700.000".
Emails and notifications in the guest's language
Confirmation emails are often sent from a queue, with no request, so the locale is the default from config/app.php. Save the guest's language in a locale column, then let Laravel use it:
use Illuminate\Contracts\Translation\HasLocalePreference;
class User extends Authenticatable implements HasLocalePreference
{
public function preferredLocale(): string
{
return $this->locale; // 'ja'
}
}
$user->notify(new BookingConfirmed($booking)); // uses lang/ja on its own
$user->notify((new BookingConfirmed($booking))->locale('ar')); // or name it directly
With HasLocalePreference, Laravel uses preferredLocale() for notifications and mailables, queued ones included; for a mailable there's also Mail::to($user)->locale('ja'). On a Node server, don't call i18next.changeLanguage per request on one shared instance, because requests arriving at the same time overwrite each other's language; use i18next.getFixedT(lng) per request.
⚠️ Why does the server send the wrong language?
split(',')[0]. It ignores q and the list of supported languages.- Locales with a hyphen in Laravel.
ar-EGmakestrans_choicealways pick the first piece. Name the folderlang/arorlang/ar_EG; turnja_JPintoja-JPbefore writing it into<html lang>. Alangcookie from JavaScript also has to be excluded inencryptCookies. - Formatting without options on a hydrated page. Rupiah with 0 decimals in Node and 2 in Firefox or Safari, UTC hours on the server: a hydration mismatch.
- Queued emails in the default language. Use
HasLocalePreferenceor->locale().
TL;DR: The server picks the language from, in order, the URL prefix, the user's locale, a cookie, then Accept-Language sorted by q (ja,en-US;q=0.7,en;q=0.3), with the source language as the fallback. Laravel's getPreferredLanguage() returns the underscore style (ja_JP), so use the list ['en', 'id', 'ja', 'ar'] that matches the lang/ folders, then App::setLocale() in a middleware. __() and trans() fetch text, trans_choice picks a | piece by number from Laravel's own table (not ICU), and a locale with a hyphen makes it always pick the first piece. Send <html lang dir>, Content-Language and Vary. A hydration mismatch appears when the server and the browser format differently (Node 22 "Rp 700.000", Chrome 147 and Firefox "Rp 700.000,00", UTC hours against the homestay's zone): write the options, or format once on the server. Emails use the guest's language through HasLocalePreference or ->locale('ja').
⚡ Accept-Language, sorted by q
Write:
negotiate('en;q=0.5,ja', SUPPORTED, 'en-US'); // 'ja-JP': q 1 wins
Guess first: for the header en;q=0.5,ja, which language does the old code header.split(',')[0] pick?
en, even though ja has q 1. Without q, the weight is 1.
Meaning: Sort by q, then take the first language that's supported: an exact match first, then the same language (ja matches ja-JP).
⚡ A middleware picks, App::setLocale sets
Write:
App::setLocale(collect($candidates)->first(fn ($l) => in_array($l, self::SUPPORTED, true)) ?? 'en');
Meaning: The SetLocale middleware reads in order: the URL prefix, the logged-in user's locale, the cookie, then Accept-Language. The first one that's there and supported wins. App::setLocale() changes the locale for this request only.
⚡ trans_choice isn't ICU
Write:
trans_choice('booking.nights', 3); // "3 ليالٍ"
Meaning: Laravel splits the text at | and picks a piece by its number from its own table. Laravel's locale names use underscores: with App::setLocale('ar-EG'), trans_choice always takes the first piece.