Enable next-i18next to handle internationalization, export all pages with next export, and ensure that 404 error pages are displayed on non-generated pages

After carefully following the guidelines provided by i18next/next-i18next for setting up i18n and then referring to the steps outlined in this blog post on locize on how to export static sites using next export, I have managed to successfully generate localized versions of each page.

However, the issue arises when pages that have not been statically generated end up returning a 404 error, despite having fallback: true set in the return object of getStaticPaths. The page functions correctly on localhost but encounters this problem when deployed with Vercel.

Here is the code snippet:

const ArticlePage: NextPageWithLayout<Props> = ({ article }: Props) => {
    const { i18n, t } = useTranslation('page/news/article')

    const router = useRouter()

    if (router.isFallback) return <div>Loading...</div>

    return <div>Article</div>
}

export const getStaticPaths: GetStaticPaths = async () => {
    let paths: { params: { aid: string; locale: TLocale } }[] = []

    try {
        const response = await api.get(`/articles?per_page=9999`)
        const articles = response.data.data as IArticle[]

        articles.forEach((a) => {
            getI18nPaths().forEach((p) => {
                paths.push({
                    params: {
                        aid: a.base_64_id,
                        locale: p.params.locale,
                    },
                })
            })
        })

        return {
            paths,
            fallback: true,
        }
    } catch (error) {
        return {
            paths,
            fallback: true,
        }
    }
}

export const getStaticProps: GetStaticProps = async ({ locale, params }) => {
    try {
        const article = await api.get(`/articles/${params?.aid}`)

        return {
            props: {
                ...(await serverSideTranslations(locale || 'en', [
                    'footer',
                    'header',
                    'misc',
                    'page/news/index',
                    'page/news/article',
                ])),
                article: article.data as IArticle,
            },
        }
    } catch (error) {
        return {
            notFound: true,
        }
    }
}

ArticlePage.getLayout = function getLayout(page: ReactElement) {
    return <Layout>{page}</Layout>
}

export default ArticlePage
"i18next": "22.4.9",
"next-i18next": "^13.1.5",
"react-i18next": "^12.1.5",

A warning message appears in the console saying

react-i18next:: You will need to pass in an i18next instance by using initReactI18next
when accessing a non-generated page (in addition to the not-found error). A relevant issue has been raised regarding this warning, though finding a solution within it has proven challenging: https://github.com/i18next/next-i18next/issues/1917.

Various attempts have been made to address this issue:

  • including revalidate: 10 in the return object of getStaticProps
  • utilizing fallback: 'blocking'
  • experimenting with different variants of localePath in next-i18next.config, including the recommendation highlighted here: https://github.com/i18next/next-i18next#vercel-and-netlify
  • adding react: { useSuspense: false } to next-i18next.config
  • trying out combinations of the above solutions

Answer №1

According to the documentation, it is mentioned that next export does not have support for fallback: true. In hindsight, I realize that I should have used next build instead. This command also generates static HTML during build time and allows for runtime fetching if the requested resource is missing.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The z-index overlapping problem in webkit browsers is a result of Angular 7 animations

I have implemented staggered animations in my Angular 7 application to bring elements to life upon page load. However, I am facing a strange z-index problem with one of my components. Here is the animation code: @Component({ selector: 'track-page& ...

Exploring Objects using the for-in loop in ReactJS

This code is written in Reactjs. I am attempting to iterate through and print object data, but I keep encountering an error --> TypeError: Cannot read properties of undefined (reading 'state'). Could someone please help me identify what I am d ...

Substitute empty spaces and organize the text layout

I'm struggling to figure out how to substitute the whiteSpace in an aggregate request using MongoDB and also how to remove a specific part of a string (most likely requiring regex). Here's an example of my document: { "_id": "57dfa5c9xxd76b ...

What are the steps to troubleshoot CSS issues in NextJS?

Currently, I am encountering challenges while trying to integrate markdown with CSS. The problem I am facing has been replicated in the link provided: https://codesandbox.io/s/react-quilljsbasic-forked-3rcxw?file=/src/App.js ...

Troubleshooting Next.js 13: Issues with Error and Not Found Pages Rendering Incorrectly

I am currently working on a project with the latest version of Next.js, specifically Next.js 13, and I have organized my app directory structure accordingly. Within the app/sample directory, I have implemented custom error handling by creating pages named ...

Ways to eliminate the unusual dashed space in ReactJS using Bootstrap

While developing an app with NextJS and Bootstrap, I noticed a strange dashed gap at the top of the screen in the elements tab. Despite checking for margin or padding-top properties on any element, there doesn't seem to be a clear cause for this issue ...

Condensed JQuery condition code for "if" statement

This piece of code is designed to sequentially display 10 questions and control the visibility of each question using the CSS class .hideme. It also sends metrics data to Google Analytics. Although it functions properly, I feel like the code is too leng ...

Indicate the end of the row in JavaScript when using the match() function

What's the best way to identify the end of a row when using the match() function? I'm trying to extract "2021 JANUARY 18 MONDAY" from this page. If there is additional text after the desired string, I typically use this code: var content = UrlFe ...

What is the best way to create a list using only distinct elements from an array?

If I have a collection of different colors: Red Blue Blue Green I aim to extract only the unique colors and store them in an array. Subsequently, I plan to incorporate each color from that array into an existing color list. The desired outcome would l ...

The shadow feature in Three.js doesn't seem to be functioning properly

I'm having trouble getting the Three.js shadow effect to work in version r82. I believe I have everything set up correctly, but for some reason it's not working. Can anyone point out what I might be missing? Here is an example link for referen ...

What is the best way to update or reload an embedded application/pdf?

I have implemented an embed code using application/pdf in order to display a pdf document on the website. To dynamically change the src attribute of the embed when a link is clicked, I utilized javascript. I confirmed this action by displaying alerts to e ...

Developing an interactive form for instant price calculations

I'm currently tackling a project that involves developing an order form capable of computing the price of a door in real-time. However, I am having trouble deciding on the best approach to take. The form will include the following inputs: Frame (Dr ...

Caution: Discrepancy found in Prop className between server and client rendering in a React SSR application

Currently, I am working on integrating a collapsible sidebar into my React application that relies on a value stored in the local storage. The intended behavior is for the sidebar to have the className of "inline" if the value is true, and "hidden" if the ...

I am looking to include query string variables within JSON key-value pairs

On my webpage, I have a .asp page using the following url: page.asp?id=33&album=ourcookout The page.asp file then calls a file.js script. Within the file.js script, there is a line located under a function that reads as follows: url: "post_file.php", M ...

Issue with displaying select options in React-hook-form when used with react-select AsyncSelect: selected labels are not being

I am currently developing a webpage that includes a form in edit mode. The form utilizes react-hook-form. When the page loads, I retrieve data from the backend (I'm using NextJs) and then assign this data to the elements within the form. Here is an ex ...

Basic JavaScript framework centered around the Document Object Model (DOM) with a module structure similar to jQuery. Currently facing challenges with

In order to create a simple framework with jQuery style, I have written the following code: (function(window) { window.smp=function smpSelector(selector) { return new smpObj(selector); } function smpObj(selector) { this.length = 0; if (!s ...

Mapping an HTTP object to a model

Currently facing an issue with mapping an http object to a specific model of mine, here is the scenario I am dealing with: MyObjController.ts class MyObjController { constructor ( private myObj:myObjService, private $sco ...

Connecting JSON objects based on unique GUID values generated

I am in search of a method to automate the laborious task of linking multiple JSON objects with random GUIDs. The JSON files are all interconnected: { "name": "some.interesting.name", "description": "helpful desc ...

When using Promise.all(), it surprisingly gives back an array of Promise <Pending>'s that are undefined, even though other solutions produce successful results

Currently, I am in the process of developing a web application that enables users to access a dashboard displaying various items. Each item comprises sections labeled as a, b, and c, which are represented as complete (o) or incomplete (x) on the dashboard. ...

The functionality of JQuery TableSorter is not responsive when a user clicks on it

I seem to be running into an issue on my website where I can't get the JQuery TableSorter to work properly. When I attach it to a table for sorting, nothing happens when I click on the headers. The table remains static and unsortable. Here's a s ...