Complete the code to get the user's preferred language from the browser in Next.js.
const userLocale = [1] || 'en';
The navigator.language property returns the browser's preferred language as a string, such as 'en-US'.
Complete the code to detect locale from the URL pathname in Next.js.
const locale = router.[1].split('/')[1] || 'en';
router.pathname which may not reflect the actual URL.router.query which is an object, not a string.router.asPath gives the actual URL path including locale prefix, which we split to get the locale.
Fix the error in this Next.js middleware code to correctly detect locale from the request headers.
const locale = req.headers.get('[1]')?.split(',')[0] || 'en';
content-language which is a response header.user-language which is not a standard header.The accept-language header contains the user's preferred languages in order.
Fill both blanks to create a Next.js middleware that redirects to the locale path if missing.
if (!req.nextUrl.pathname.startsWith('/[1]')) { return NextResponse.redirect(new URL('/[2]' + req.nextUrl.pathname, req.url)); }
This middleware checks if the path starts with '/en' and redirects to add '/en' if missing.
Fill all three blanks to create a Next.js server component that shows the detected locale from headers.
export default async function LocaleDisplay() {
const locale = headers().get('[1]')?.split(',')[0] || '[2]';
return <p>Your locale is: [3]</p>;
}The component reads the 'accept-language' header, defaults to 'en', and displays the locale inside a paragraph.