Internationalization in Next.js error files
The Next.js App Router's file convention provides two files that can be used for error handling:
This page provides practical guides for these cases.
Have a look at the App Router example to explore a working app with error handling.
not-found.js
Next.js renders the closest not-found
page when a route segment calls the notFound
function (opens in a new tab). Since the [locale]
segment is used to localize your app, the not-found
page needs to be located within this route segment too.
import {useTranslations} from 'next-intl';
export default function NotFoundPage() {
const t = useTranslations('NotFoundPage');
return <h1>{t('title')}</h1>;
}
Note however, that Next.js will only render this page when the notFound
function is called from within a route, not for all unknown routes in general.
Catching unknown routes
To catch unknown routes too, you can define a catch-all route that explicitly calls the notFound
function.
import {notFound} from 'next/navigation';
export default function CatchAllPage() {
notFound();
}
After this change, all requests that are matched within the [locale]
segment will render the not-found
page when an unknown route is encountered.
Catching non-localized requests
When the user requests a route that is not matched by the next-intl
middleware (depending on your matcher
config), there's no locale associated with the request (e.g. /unknown.txt
). You can add a root not-found
page to handle these cases too.
'use client';
import Error from 'next/error';
// Render the default Next.js 404 page when a route
// is requested that doesn't match the middleware and
// therefore doesn't have a locale associated with it.
export default function NotFound() {
return (
<html lang="en">
<body>
<Error statusCode={404} />
</body>
</html>
);
}
Note that a root layout file is required in this case, even if it's just passing children
through (opens in a new tab).
error.js
When an error
file is defined, Next.js creates an error boundary within your layout (opens in a new tab) that wraps pages accordingly to catch runtime errors:
Since the error
file must be defined as a Client Component, you have to use NextIntlClientProvider
to provide messages in case the error
file renders.
If you've set up next-intl
to be used in Client Components, this is already the case and there's no additional setup needed. If you're using the Server Components beta though, you have to provide the relevant messages in the wrapping layout.
Once NextIntlClientProvider
is in place, you can use functionality from next-intl
in the error
file:
'use client';
import {useTranslations} from 'next-intl';
export default function Error({error, reset}) {
const t = useTranslations('Error');
return (
<div>
<h1>{t('title')}</h1>
<button onClick={reset}>{t('retry')}</button>
</div>
);
}