Skip to content

Translated 404 pages

When having a translated website, it makes sense to have your 404 pages translated as well! This can be achieved fairly easily using this package.

Hybrid or server

This method is actually the easiest. We are going to create a server rendered 404 page that will allow to show the content in the current locale dynamically!

First, create a new page at src/pages/404.astro. It’s important to put in the pages directory and not the routes directory to prevent the integration from generating one per locale.

The important part here is to make sure the page is not prerendered! If you’re in hybrid mode, make sure to add export const prerender = false.

You can then use any utility from this package without any issue! For example:

src/pages/404.astro
1
---
2
import Layout from "~/layouts/Layout.astro";
3
import { getLocale, t } from "i18n:astro"
4
5
export const prerender = false;
6
7
const locale = getLocale()
8
const title = t("404:pageNotFound");
9
---
10
11
<Layout {title}>
12
<h1>{title}</h1>
13
<p>Locale: {locale}</p>
14
</Layout>

Static

If you want to keep your site fully static, you’ll want to generate a 404 page per locale and rewrite paths with your hosting provider. Below we’ll have a look with Vercel and Netlify.

Creating the page

First, create a new page at src/routes/404.astro. You can use any utility from this package without any issue! For example:

src/pages/404.astro
1
---
2
import Layout from "~/layouts/Layout.astro";
3
import { getLocale, t } from "i18n:astro"
4
5
const locale = getLocale()
6
const title = t("404:pageNotFound");
7
---
8
9
<Layout {title}>
10
<h1>{title}</h1>
11
<p>Locale: {locale}</p>
12
</Layout>

Creating rewrites

Now that we have 404 pages available (eg. at /404 and /fr/404), we need to tell the host to rewrite the path to the right locale.

vercel.json
1
{
2
"$schema": "https://openapi.vercel.sh/vercel.json",
3
"rewrites": [
4
{
5
"source": "/(?<lang>[^/]*)/(.*)",
6
"destination": "/$lang/404/"
7
}
8
]
9
}

Handling the "prefix" strategy

If you strategy: "prefix" in your integration config, we need to make an adjustement. Following the previous steps, the following 404 are available: /en/404 and /fr/404. What happens if someone visits /test? It will show the default host 404, not ideal.

What you can do instead is to duplicate your src/routes/404.astro to src/pages/404.astro to handle this case. No other action is required!