next-i18next: Error: `pages/404` can not have getInitialProps/getServerSideProps

Describe the bug

After setting up next-i18next, I have the following error in the terminal on every page (probably because it’s looking for an not existing favicon.ico by default).

Error: `pages/404` can not have getInitialProps/getServerSideProps, https://err.sh/zeit/next.js/404-get-initial-props

But my 404 page is really simple, no getInitialProps/getServerSideProps

export default () => <h1>This is the 404 page</h1>

Note: i’m trying the setup the project for a potential future translation. Therefore, next-i18next provides a clean way for developers to use the system as string dictionary for UI texts, which later on could be translated.

Obviously, if I go to /404, I see the error in browser.

Thank you!

Occurs in next-i18next version

From the package-lock.json and other info

  • next-i18next: 4.2.1
  • i18next: 19.3.4
  • node JS: 13.9.0
  • npm: 6.13.7

Steps to reproduce

File structure

└── public
    └── static
        └── locales
            ├── en
               └── common.json
               └── homepage.json
└── src
     └── pages
     └── components

In i18n.js Note: I needed to add those properties in the config to be able to make t('key) working

lng: 'en',
fallbackLng: 'en',
languages: ['en', 'not-existing-yet'],

More specifically lng: 'en', the fallbackLng is for later if we do add more languages, and languages to be able to access i18n.languages (otherwise it wasn’t working)

const NextI18Next = require('next-i18next').default

const NextI18NextInstance = new NextI18Next({
  defaultLanguage: 'en',
  lng: 'en',
  fallbackLng: 'en',
  languages: ['en', 'not-existing-yet'],
  otherLanguages: ['not-existing-yet'],
})

module.exports = NextI18NextInstance;

In _app.js

import React from "react";
import App from "next/app";

// i18n
import { appWithTranslation } from '~/i18n'

class MyApp extends App {
  render() {
    const { Component, pageProps } = this.props;

    return (
      <>
            <Head>
              <title>NextJS Advanced Routing</title>
            </Head>
            
            <Component {...pageProps} />
      </>
    );
  }
}

export default appWithTranslation(MyApp);

In index.js (homepage)

import { withTranslation } from '~/i18n'

const Index = ({ data, t, ...props }) => {
   return (
     <h1>{ t('homepage:title') }</h1>
   )
}

Index.getInitialProps = async ({ query }) => {
  // get some data
  const data = await getData();
  return { data, namespacesRequired: ['common', 'homepage'], }
}

export default withTranslation('homepage')(Index)

Expected behaviour

404 should be working without triggering an error

Screenshots

OS (please complete the following information)

  • Device:MBP 2019 15"
  • Browser: Chrome 80.0.3987.149

Additional context

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 49
  • Comments: 29 (8 by maintainers)

Most upvoted comments

I’ve stumbled upon this discussion but couldn’t find the solution right away here, so I’m posting it for future reference:

This solution uses "next-i18next": "^8.2.0" with "next": "^10.2.0"

// pages/404.tsx
import { GetStaticProps } from 'next'
import NextErrorComponent from 'next/error'
import { useTranslation } from 'next-i18next'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'

export const getStaticProps: GetStaticProps = async ({ locale }) => {
  return {
    props: {
      ...(await serverSideTranslations(locale ?? 'en', ['common'])),
    },
  }
}

const NotFoundPage = () => {
  const { t } = useTranslation()
  return <NextErrorComponent statusCode={404} title={t('error.title')} />
}

export default NotFoundPage

Just to follow up: I don’t think it’s right to disable the warning. I think the correct thing to do is translate our 404 pages.

I can speak to the NextJs team about this.

Actually this Next’s requirement is absurd, cause if you have translations you must translate your custom 404 as well.

Yeah. I’m facing the same issue now. I like to keep my console clean. But in this particular situation I get or warning from Next.js You should have custom 404 page because it's good to optimize its as static content either warning from next-18next You have not declared a namespacesRequired array on your page-level component: Custom404.

Frustrating 😞

I’ve stumbled upon this discussion but couldn’t find the solution right away here, so I’m posting it for future reference:

This solution uses "next-i18next": "^8.2.0" with "next": "^10.2.0"

// pages/404.tsx
import { GetStaticProps } from 'next'
import NextErrorComponent from 'next/error'
import { useTranslation } from 'next-i18next'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'

export const getStaticProps: GetStaticProps = async ({ locale }) => {
  return {
    props: {
      ...(await serverSideTranslations(locale ?? 'en', ['common'])),
    },
  }
}

const NotFoundPage = () => {
  const { t } = useTranslation()
  return <NextErrorComponent statusCode={404} title={t('error.title')} />
}

export default NotFoundPage

I came from google. It works! Saved my time. Thank you. Hopefully we do not need getServerSideProps on 404 page.

Any updates?

@Dynkin, you can add your custom 404 page without the getInitialProps. Actually i’m running with this solution. it’s not the best solution but it’s working.

import PropTypes from 'prop-types';
import { withTranslation } from '../i18n';

function Custom404({ t }) {
  return (
    <div>
      <h1>{t('title-message')}</h1>
    </div>
  );
}

Custom404.propTypes = {
  t: PropTypes.func.isRequired,
};

export default withTranslation('404')(Custom404);

Hello, you are right we should be able to translate the 404 page as well ! (great job on this repo btw)

Is it possible to disable the warning though ? Because all my other pages are correctly setup and I would like to avoid to be spamed by the warning when navigating to the 404 page.

Thank you !

Yeah, @Danetag this is probably an issue to raise with the NextJs team. There’s not much that can be done on the next-i18next side of things - we have to get translations somehow.

This works for me. On my specific case I need to import both footer and errors locale.

import { useTranslation } from 'next-i18next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';

export default function Custom404() {
  const { t } = useTranslation('errors');

  return (
    <div>
      <h1>404</h1>
      <p>{t('404')}</p>
    </div>
  );
}

export async function getStaticProps(context: any) {
  let localisation = {};
  if (context.locale) {
    localisation = await serverSideTranslations(context.locale, ['errors', 'footer']);
  }

  return {
    props: {
      ...localisation,
    },
  };
}

I spend an afternoon fiddling with this I managed to get the following to work

import { GetServerSideProps, NextPage } from 'next';
import { SSRConfig } from 'next-i18next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import React, { useEffect, useState } from 'react';
import { useTranslation, withTranslation } from 'react-i18next';
import { Footer } from '../components/footer/footer';
import { Navigation } from '../components/navigation/navigation';
import { NotFoundHero } from '../components/not-found/notFoundHero';

export type NotFoundPageProps = SSRConfig & { locale: string };

const Page404Component: NextPage<NotFoundPageProps> = ({ locale }) => {
	const { t } = useTranslation();
	const [menus, setMenus] = useState([]);
	const loadMenus = async () => {
		const res = await fetch(`/api/menus?locale=${locale}`);
		const menus = await res.json();
		setMenus(menus);
	};
	useEffect(() => {
		loadMenus();
	}, []);
	return (
		<main>
			<Navigation menus={menus} slugs={{}} />

			<NotFoundHero
				title={t('notfound.title')}
				description={t('notfound.description')}
				imageDescription={t('notfound.imageDescription')}
			/>

			<Footer menus={menus} slugs={{}} />
		</main>
	);
};

export const getStaticProps: GetServerSideProps<NotFoundPageProps> = async ({
	locale,
	preview,
}) => {
	const translations = await serverSideTranslations(locale, ['common']);

	return {
		props: {
			locale,
			...translations,
		},
	};
};

const Translated404Page = withTranslation('translations')(Page404Component);

const Page404 = (props) => {
	return <Translated404Page {...props} useSuspense={false} />;
};

export default Page404;

the important part was to use withTranslation to get the translation context and to disable suspense as it is not yet supported. basically this allows a for a fully translated 404 page with client side data fetching for additional stuff like navigation etc.

New to next.js and currently fiddling around to solve the same problem.

I noticed, that if I don’t have a 404.js page, it will fallback to the _error.js page to display the 404 Error and inside _error.js it is possible to use “getInitialProps”.

I am using that for now as a workaround. It solves the translation problem, but it does cause another warning:

“You have added a custom /_error page without a custom /404 page. This prevents the 404 page from being auto statically optimized.”

Still having this issue using "next-i18next": "^13.2.2" and "next": "13.3.1" I try to create pages/404.tsx

import Button from '@/components/ui/Button'
import { GetStaticProps, NextPage } from 'next'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import Image from 'next/image'

const Custom400Page: NextPage{}> = ({}) => {
  return (
    <div className='flex flex-col items-center justify-center'>
      <Image src='/images/500.svg' alt='500 Error Icon' width={200} height={135} />
      <h1 className=''>Internal System Error</h1>
      <span>Something went wrong at our end. Back to home to refresh your page.</span>
      <Button id='back-to-home' handleClick={() => {}} text='Home' />
    </div>
  )
}

export const getStaticProps: GetStaticProps = async ({ locale }) => {
  return {
    props: {
      ...(await serverSideTranslations(locale ?? 'en', ['common'])),
    },
  }
}

export default Custom400Page

upon building the app, it shows bunch of errors:

Error occurred prerendering page "/id/404". Read more: https://nextjs.org/docs/messages/prerender-error
Error occurred prerendering page "/en/404". Read more: https://nextjs.org/docs/messages/prerender-error

info  - Generating static pages (2/2)

> Export encountered errors on following paths:
        /404: /en/404
        /404: /id/404
error Command failed with exit code 1.

Any updates on this? 👀

@CalebLovell As next-i18next@beta supports other data-fetching methods, this should no longer be an issue. See #869.