i18n Integration
next-api-layer provides built-in support for internationalization (i18n), automatically detecting the user's locale and injecting it into API requests.
How It Works#
- Middleware extracts locale from URL path (e.g.,
/tr/blog→tr) - Sets
x-localeheader on the response (accessible viaheaders().get('x-locale')) - API Client reads the header and appends
?lang={locale}to backend requests
Configuration#
Auth Proxy (Middleware)#
API Client#
Configuration Options#
i18n (Proxy)#
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| enabled | boolean | false | Enable i18n locale detection |
| locales | string[] | [] | Valid locale codes to detect |
| defaultLocale | string | - | Fallback locale when not detected |
| middleware | function | - | i18n middleware function (e.g., next-intl). Library calls it and merges responses automatically |
i18n (API Client)#
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| enabled | boolean | false | Enable i18n parameter injection |
| paramName | string | 'lang' | Query parameter name |
| locales | string[] | [] | Valid locale codes |
| defaultLocale | string | - | Fallback locale |
With next-intl#
When using with next-intl, simply pass your intl middleware to the middleware option. The library handles response merging automatically, preserving all critical headers and cookies:
The library automatically:
- Calls your i18n middleware internally
- Preserves
x-locale,x-auth-user, andx-refreshed-tokenheaders - Copies all auth cookies to the merged response
- Handles both API routes and page routes correctly
Advanced: Manual Middleware Control#
If you need more control over middleware execution, you can still use the afterAuth hook instead:
Backend Implementation#
Your backend needs to filter content based on the lang query parameter:
Go (Fiber)#
Laravel#
Django#
Database Schema#
Add a lang column to your content tables:
Example: Full Setup#
1. Middleware (proxy.ts)#
2. API Client (lib/api.ts)#
3. Route Handler (app/api/posts/route.ts)#
4. Page Component (app/[locale]/blog/page.tsx)#
Supported Locales#
The library doesn't restrict which locales you can use. Common examples:
- ISO 639-1:
en,tr,ar,es,fr,de,ja,ko,zh - With region:
en-US,en-GB,pt-BR,zh-CN,zh-TW
Just ensure your locales array in config matches your URL structure and backend expectations.