How to internationalize an AstroJS website while maintaining good SEO ?
Preparation
Setup the languages and translations
First, we need to create a /src/i18n
folder which contains the languages and the translations. Here is my current implementation:
Create the pages
/src/pages/[lang]/index.astro
Problem
AstroJS renders ComponentUsingI18n
twice :
- One time on server (to generate HTML files)
- One time on client (to hydrate it and make it dynamic)
So, we will need to pass 2 times the lang
variable.
⚠️ The JS Components have to render the same DOM elements, else the hydratation won’t work. And we don’t have the Astro.params.lang
variable in JSX/TSX components.
If HTML server side and client side is different, we would have errors like:
Warning: An error occurred during hydration. The server HTML was replaced with client content in <astro-island>.
How my solution works
A schema is better than 1000 words:
Loading graph...
Implementation with code
Render the components server side
I created a SessionStorage
for the server Astro:
Then, I called on every astro pages:
Render the components client side
When the frontend is rendered by the client, we do:
And we won’t forget to add in Astro layout :
Refactoring : useTranslation()
hook
Implementation
To create a common hook, first, we need to find the runtime. I use this function:
My hook looks like this:
Usage
To ensure i18n is properly set up on every page, you should include this code at the beginning of each file.
And to write a component using i18n, we will do something like:
On my side, I have no problems to render and hydrate this component !
Thank you for reading my blog post !
Practice code with the "Quick Sort" algorithm
Enhance your coding skills by learning how the Quick Sort algorithm works!
The SOLID/STUPID principles
Learn what are the SOLID and STUPID principles with examples
Create a Docker Swarm playground
Let's create Docker Swarm playground on your local machine
Create an Ansible playground with Docker
Let's create an Ansible playground with Docker
HashiCorp Vault - Technological watch
Learn what is HashiCorp Vault in less than 5 minutes !
Setup a Kubernetes cluster with K3S, Traefik, CertManager and Kubernetes Dashboard
Let's setup step by step our own K3S cluster !
LFTP - Deploy an application in command line
Here we will see how to automatically deploy an application with lftp in command line.
Create a WAMP environment with docker
An easy code to install Apache, MySQL and PHP with Docker !