乐闻世界logo
搜索文章和话题

How to access current language in getStaticProps Next. Js ?

1个答案

1

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.

  1. Configure i18n in next.config.js:

    javascript
    module.exports = { i18n: { locales: ['en', 'fr'], defaultLocale: 'en', // Set path to include language information localeDetection: false }, };
  2. Use dynamic routing in page components: You can create dynamic routes such as pages/[lang]/posts.js, and then use the lang parameter within getStaticProps to determine the content language.

    javascript
    export 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.

  1. Set a cookie on the client: When the user selects a language, set a cookie to store this choice.

    javascript
    document.cookie = "NEXT_LOCALE=fr; path=/; max-age=31536000"; // Set to French, valid for one year
  2. Read the cookie in getStaticProps: Since getStaticProps runs on the server side, you need to use a third-party library (such as cookie) to parse cookies. You can retrieve these cookies from the req object in the context parameter.

    javascript
    import 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.

javascript
export 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.

2024年6月29日 12:07 回复

你的答案