Updated
NOTE! This article is in development and is using a temporary URL. It is not safe to refer to it or use the information it contains.
How do I use the Next.js to automatically serve resources in the language requested by an HTTP request?
When a user agent requests a document from a server, information about the user's language preferences is typically passed to the server via the HTTP Accept-Language
header. If the server stores versions of a page in more than one language, this HTTP information can be used to retrieve the page in the user's preferred language, if it is available. If there is only one version of a page on the server, that version will be retrieved.
The mechanism of choosing the relevant page to return to the user, based on the Accept-Language
information in the HTTP request, is referred to as language negotiation.
In many cases, the initial user agent setting is okay. For example, if you have a Japanese version of a browser, the browser typically assumes that you prefer pages in Japanese, and sends this information to the server. Mainstream browsers allow you to modify these language preferences. For more information see Setting language preferences in a browser.
In this article, we’ll walk through how to implement language negotiation in a Next.js application using the Accept-Language header, enabling your site to automatically serve localized content that matches a user’s language preferences.
Next.js includes automatic locale detection based on the Accept-Language header. When enabled, users are automatically redirected to their preferred language path.
In your next.config.ts
file, configure the i18n
field:
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
localeDetection: true, // Enable automatic locale detection
},
};
export default nextConfig;
With this configuration, a user with Accept-Language: fr
will be redirected to /fr
.
When the user is redirected to /fr
, Next.js looks for pages and content under the fr
locale. How you should organize that content will be the topic of a future article.
You can test your implementation by manually sending an HTTP request with the Accept-Language
header:
curl -H "Accept-Language: fr" http://localhost:3000/
You should receive a redirect to /fr
.
Set language preferences in browsers and verify automatic redirection.