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

Update the image on a webpage within a template using AJAX code

I manage a website that utilizes templates. Within the template, there is a main image that I need to replace on specific pages, not throughout the entire site. I am seeking a way to change this main image to a new one on select pages using Ajax. Upon re ...

How can you display an alert message when new data is successfully added to a database using ajax?

In my web application, I have implemented a functionality to display an alert message when new data is successfully inserted into the database. The Ajax code below is responsible for sending a request to the EditDeleteLecture.php file. However, a challenge ...

``There is an issue with getServerSideProps when wrapping it in a

When attempting to implement an auth handler function around getServersideProps, I encountered the following error message: TypeError: getServerSideProps is not a function The wrapper code in question is as follows: export async function protect(gssp) { ...

Is there a way to retrieve YouTube URLs through programming automation?

I'm currently working on a project to automatically retrieve YouTube URLs and incorporate a download button feature. I found a tutorial suggesting the use of 'ytplayer.config.args.url_encoded_fmt_stream.map.split(",");' After attempting to ...

Utilize React hook form to easily manage separate forms and buttons with the useFormContext

I am currently working on creating a customizable popup in Chakra-UI. The idea is to have a modal where different forms can be passed in, with the form displayed in the modal body and buttons in the modal footer. Everything seems to render correctly withou ...

On two separate computers, create-next-app is encountering the identical error message: "Router received an invalid href parameter."

Just tested this on 2 different computers and I'm getting the same errors every time I create a brand-new project with create-next-app. Didn't used to get this error before. What happened? https://i.stack.imgur.com/7wOqA.jpg ...

My initial venture into Solidity DApp development, Encounter of an Unresolved Runtime

As I embark on developing my inaugural Solidity DApp using Next.js and Hardhat, I've encountered a perplexing error. After successfully deploying my contract on a local blockchain via npx hardhat node, the issue arises when calling the getProposalCoun ...

What could be causing the error message "CSRF token missing or incorrect" to appear?

I am facing an issue with returning a value from a View function in Django. This particular function is called from a JavaScript code using Ajax, but I'm encountering an error that says 'Forbidden (CSRF token missing or incorrect)'. JavaScr ...

"Sending a POST request from the smartphone application client developed using the Meteor

I'm currently working on a simple mobile app with Meteor that aims to send user location data to a geospatial database or server. However, I'm facing some challenges and uncertainties about the feasibility of this task using Meteor. The issue ari ...

Error encountered when attempting to initiate a second screenshare on Chrome due to an invalid state

I am interested in utilizing Screensharing in Chrome. After following a guide and creating an extension to access the deviceId for getUserMedia, I was able to successfully start streaming my screen. However, when I attempted to stop the stream using the pr ...

What is the best way to adjust the height of a container to equal the viewport height minus a 300px height slider?

Forgive me for the rookie question, I know what I want to achieve should be simple but I seem to be having trouble articulating it in my search for solutions. Essentially, I am trying to set a section in HTML to the height of the viewport minus the height ...

jQuery alert: A TypeError was caught stating that the object being referred to does not have the 'dialog' method available

For a few days now, I have been tirelessly searching for a solution to this issue and it has caused me quite a bit of stress. My problem lies in echoing a JQuery popup script within php: echo '<link rel="stylesheet" href="http://code.jquery.c ...

Struggling to create a regular expression for a particular scenario

I'm dealing with nodes and currently faced with the task of applying a UNIX-like grep command to filter out specific content from an HTTP GET response. Below is the raw text received as the body variable: <?xml version="1.0" encoding="UTF-8" stand ...

The display and concealment of a div will shift positions based on the sequence in which its associated buttons are clicked

I am in need of assistance with coding (I am still learning, so please excuse any syntax errors). What I am trying to achieve is having two buttons (button A and button B) that can toggle the visibility of their respective divs (div A and div B), which sh ...

How can I resolve the issue if a specific file within a package cannot be located using NPM?

What are the steps to troubleshoot when a file inside a package cannot be located? Error: Module not found: Can't resolve 'images/loading-icon.gif' ./node_modules/react-pdf-highlighter/node_modules/pdfjs-dist/web/pdf_viewer.css I'm cur ...

Instructions on how to navigate to a class page by clicking a button in a ReactJS interface

I am currently working with React and have implemented 3 classes in separate files. The App.js file contains a navbar and button, which when clicked, displays a table from 'Table.js'. I have also added buttons in front of each row in the table th ...

Updating the state using ui-router

The application consists of pages labeled as X, Y, and Z. The intended route is to navigate from page X to select details, then move onto page Y to select additional details, and finally land on page Z. I wish that upon clicking the window's back butt ...

Javascript Error: Page reload interrupted by Broken Pipe IOError [Errno 32]

I am facing an issue with my javascript function that sends a signal to my flask app for recalculating figures using ajax. Upon successful figure production, I want to reload the page with updated figures by adding a version number to the filename (using & ...

initiate file transfer

I am currently developing a web application using NextJS with TRPC. Within the app, there is a form that requires users to select a file. My goal is to pass this file through a TRPC call to handle all file-related logic on the backend rather than the front ...

Direct a flow to an unknown destination

What I am trying to achieve is writing a stream of data to nowhere without interrupting it. The following code snippet writes the data to a file, which maintains the connection while the stream is active. request .get(href) .on('response', func ...