How to Detect User Language in Next.js Easily
Accept-Language header in server-side functions like getServerSideProps or middleware. Alternatively, use Next.js built-in internationalized routing by configuring i18n in next.config.js to automatically detect and serve the user’s preferred language.Syntax
To detect user language in Next.js, you typically access the Accept-Language header from the request object in server-side code. You can do this inside getServerSideProps, middleware, or API routes.
Example parts:
context.req.headers['accept-language']: Gets the language preferences sent by the browser.next.config.jsi18nconfig: Enables automatic locale detection and routing.
export async function getServerSideProps(context) { const acceptLanguage = context.req.headers['accept-language'] || ''; // Parse or use acceptLanguage string return { props: { acceptLanguage } }; } // next.config.js module.exports = { i18n: { locales: ['en', 'fr', 'es'], defaultLocale: 'en', localeDetection: true } };
Example
This example shows how to detect the user language from the Accept-Language header in getServerSideProps and display it on the page.
export default function Home({ userLanguage }) { return ( <main> <h1>User Language Detection</h1> <p>Your browser language is: <strong>{userLanguage}</strong></p> </main> ); } export async function getServerSideProps(context) { const acceptLanguage = context.req.headers['accept-language'] || 'unknown'; // Extract the first language code before comma const userLanguage = acceptLanguage.split(',')[0]; return { props: { userLanguage } }; }
Common Pitfalls
1. Relying only on client-side detection: Detecting language only in the browser (e.g., navigator.language) can cause flicker or wrong content during server-side rendering.
2. Not parsing Accept-Language properly: The header can contain multiple languages with quality values; always parse carefully.
3. Forgetting to configure i18n in next.config.js: Without this, Next.js won’t handle locale routing or detection automatically.
/* Wrong: Client-side only detection causes flicker */ import { useEffect, useState } from 'react'; export default function Page() { const [lang, setLang] = useState(''); useEffect(() => { setLang(navigator.language); }, []); return <p>Language: {lang}</p>; } /* Right: Server-side detection in getServerSideProps */ export async function getServerSideProps(context) { const acceptLanguage = context.req.headers['accept-language'] || 'en'; return { props: { lang: acceptLanguage.split(',')[0] } }; }
Quick Reference
- Use
context.req.headers['accept-language']in server-side functions to get user language. - Configure
i18ninnext.config.jsfor automatic locale detection and routing. - Parse the
Accept-Languageheader carefully to handle multiple languages. - Avoid client-only language detection to prevent UI flicker.