Language Detection on Initial Load
Show how to detect the user's preferred language on the initial load of the application using Next.js 14 features.
import { useRouter } from 'next/router';
export default function HomePage() {
const router = useRouter();
useEffect(() => {
if (typeof navigator !== 'undefined') {
const userLang = navigator.language || navigator.userLanguage;
// Redirect to the language-specific path based on the browser language
if (userLang.startsWith('fr')) {
router.push('/fr');
} else if (userLang.startsWith('es')) {
router.push('/es');
} else {
// Default to English path
router.push('/en');
}
}
}, [router]);
return (
<div>
Detecting language...
</div>
);
}
This Next.js page component detects the user's preferred language on the initial load and redirects to a language-specific route. It uses the useRouter hook from Next.js to perform the redirection and the useEffect hook to run the detection logic after the component mounts. The 'navigator.language' or 'navigator.userLanguage' is used to determine the preferred language.
export async function getServerSideProps(context) {
const { req } = context;
const userLang = req.headers['accept-language'].split(',')[0];
// Redirect to a path with a language prefix based on the Accept-Language header
return {
redirect: {
destination: `/${userLang.startsWith('fr') ? 'fr' : userLang.startsWith('es') ? 'es' : 'en'}`, // Default to English if not French or Spanish
permanent: false
}
};
}
This code snippet is used in a Next.js page to get server-side properties and performs language detection on the server based on the 'Accept-Language' HTTP header from the incoming request. This code will cause the server to respond with a redirect to the appropriate language-specific route before the page is initially rendered to the user.
html {
/* CSS styles to show a loading message or animation */
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-family: Arial, sans-serif;
}
/* Optionally style the loading text */
div {
font-size: 20px;
color: #333;
}
This CSS styles the HTML page to center the loading message or animation while the language detection and redirection is taking place.