In Next.js, getStaticProps is a function for server-side rendering that enables you to supply necessary data as props for pages. When working with multilingual websites, accessing the current language is a common requirement. However, getStaticProps does not natively include information about the current language environment, so you need to configure it appropriately.
Method 1: Using URL Path
A common approach is to include the language identifier in the URL, such as /en/posts or /fr/posts. This can be set up by modifying the next.config.js file to configure dynamic routing.
-
Configure i18n in
next.config.js:javascriptmodule.exports = { i18n: { locales: ['en', 'fr'], defaultLocale: 'en', // Set path to include language information localeDetection: false }, }; -
Use dynamic routing in page components: You can create dynamic routes such as
pages/[lang]/posts.js, and then use thelangparameter withingetStaticPropsto determine the content language.javascriptexport async function getStaticProps({ params }) { const { lang } = params; // Fetch data based on locale const data = await fetchDataBasedOnLocale(lang); return { props: { data, }, }; }
Method 2: Using Custom Cookies or Headers
If you prefer not to display the language setting in the URL, you can instead pass it via Cookies or HTTP Headers.
-
Set a cookie on the client: When the user selects a language, set a cookie to store this choice.
javascriptdocument.cookie = "NEXT_LOCALE=fr; path=/; max-age=31536000"; // Set to French, valid for one year -
Read the cookie in
getStaticProps: SincegetStaticPropsruns on the server side, you need to use a third-party library (such ascookie) to parse cookies. You can retrieve these cookies from thereqobject in thecontextparameter.javascriptimport cookie from 'cookie'; export async function getStaticProps(context) { const { req } = context; const cookies = cookie.parse(req ? req.headers.cookie || "" : document.cookie); const currentLocale = cookies.NEXT_LOCALE || 'en'; // Default to English const data = await fetchDataBasedOnLocale(currentLocale); return { props: { data, }, }; }
Method 3: Using Next.js Internationalized Routing
If you are using Next.js 10 or later and have enabled Internationalized Routing in next.config.js, Next.js will automatically handle language detection and routing. In this case, you can directly access the current language from the locale field.
javascriptexport async function getStaticProps({ locale }) { const data = await fetchDataBasedOnLocale(locale); return { props: { data, }, }; }
The above are several methods to access the current language in getStaticProps within Next.js. Each method has specific use cases, and you can select the most appropriate one based on your project needs.