Se quiser ler esse artigo em Portugês clique aqui
Recently, I started learning Astro to create a dashboard-like project.
I really want to implement internationalization (i18n) in this project—the idea is that everyone should be able to use it, regardless of their language.
Problem
Astro’s i18n support is quite good. It works similarly to Next.js or any other framework with routing based on file/folder structure.
So, if we want to have a page in English and the same page in Portuguese, we can organize our files like this:
. └── src/ └── pages/ ├── en/ │ ├── login.astro │ └── dashboard.astro └── pt-br/ ├── login.astro └── dashboard.astro
And each page has its own i18n strings—nice!
But here’s where my problem starts: I don't want to clone all my pages; I only want to change the strings on those pages.
I need something like /[any-language-flag]/all-my-routes.
You might ask: "Why not use something like react-intl?" My answer is that I want to fully leverage Astro's engine, especially for SSG/SSR, and avoid any client components. Generally, these frameworks use React Context, which is only rendered on the client side.
Trying and Failing
First of all, I read the Astro recipe about i18n and checked out some community libraries to solve this problem.
The first library I tested was astro-i18next, and it looked like exactly what I needed!
Based on an array in the config file, astro-i18next generates my i18n pages at build time, so I only need to code once and don't have to worry about cloning pages.
The problem is that astro-i18next seems to be archived or no longer maintained. There are a lot of issues, and the last commit was over a year ago.
Solution
After trying other libraries (honorable mention to astro-i18n), I found Paraglide, and it was a game-changer for my project.
I chose Paraglide because:
- It’s type-safe, so I can use it with TypeScript and benefit from autocomplete.
- It converts i18n strings into functions, so if a string key changes, my build will fail, catching errors early.
- Using i18n functions allows for better tree shaking, removing unused functions.
- There’s a VS Code extension that enhances the development experience.
Note: You can use Paraglide in a JS project too, and it also supports Next.js.
After installation and configuration, I used my messages like this:
--- import * as m from "../paraglide/messages.js"; --- <h1 id="m-hello-name-Alan">{m.hello({ name: "Alan" })}</h1>
However, this didn't solve my routing problem—I was still cloning my pages for each language I wanted to add.
To solve this, I changed my project to use dynamic routes in the root route, so all my routes now start with the language flag.
My folder structure turned into this:
. └── src/ └── pages/ └── [lang]/ ├── login.astro └── dashboard.astro
After this change, Paraglide can automatically get the language from the route parameter:
- http://localhost:4321/en/login
- http://localhost:4321/pt-br/login
Now, I can add a new language just by setting it in astro.config.ts and translating my string file.
But I still have two more issues to solve:
- When the user first accesses http://localhost:4321/ without a language flag.
- If the user changes the language on a specific route, I need to keep them on the same route (e.g., /en/create-account should redirect to /pt-br/create-account or /pt-br/criar-conta).
Middleware for Language Redirect
To solve the first issue of language redirect, I used Astro middlewares.
In src/middleware/index.ts, I added this code:
import { defineMiddleware } from 'astro:middleware'; import { languageTag, setLanguageTag, type AvailableLanguageTag, } from '../paraglide/runtime'; export const onRequest = defineMiddleware((context, next) => { // Get lang from url param const lang = context.params.lang; // If changed if (lang !== languageTag()) { setLanguageTag(lang as AvailableLanguageTag); // Redirect to lang changed or default (en) return context.redirect(`/${lang ?? 'en'}`); } return next(); });
Language Picker with Current Route
To keep the user on the same route when they switch languages, I added this component:
--- import { languageTag } from '../paraglide/runtime'; const pathName = Astro.url.pathname.replace(`/${languageTag()}/`, ''); ---
Additionally, we could translate these messages too, using the second parameter in the Paraglide messages function:
- {m.goToLanguage(undefined, { languageTag: 'pt-br' })}
- {m.goToLanguage(undefined, { languageTag: 'en' })}
Considerations
I don't consider my solution to be the best, especially since I'm still learning Astro, so there might be other solutions. If you know of any, please comment, and I'll give them a try :)
Thanks for reading this article! If you have any questions, please comment, I’d be happy to reply.
The above is the detailed content of Creating dynamic route language for i in Astro Build. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment