Astro Websites Localization and Internalization

yanafeshchuk

yanafeshchuk

Posted on July 12, 2023

Astro Websites Localization and Internalization

In this article, you will learn the basics of Astro localization, so you can make your website multilingual to reach new markets. We’ll discuss i18n and localization best practices that will ensure that you can adapt an application to meet the cultural, language, and other requirements of a country or region you’re targeting.

Integrating your localization software with an Astro-based website is an important step to automating the localization process.

Let’s start with a walk-through on how to set up language sub-paths and connect Crowdin to your Astro project.

Getting Started with Astro localization

In this tutorial, we will use Crowdin to translate an English Astro website into French and Spanish.

Let’s see how we can initiate our project in Crowdin. Typically, you would follow these steps:

  1. Sign up for a Crowdin or Crowdin Enterprise account and create a project.
  2. Add the project name, source language, visibility and target languages. In our case, we’ll have English as the source language and French and Spanish as the target languages.
  3. Upload the content you want to translate, such as documents, strings, or multimedia files.
  4. Define your target languages and invite translators to join your project.
  5. Translators can access and translate the content directly in the Crowdin Editor, using built-in translation tools such as translation memory and glossary management.
  6. Proofreaders can review the translated content and provide feedback or approve it.
  7. Once translations are completed, you can download the translated files and use them in your website.

Astro Site Preparation

Astro is a comprehensive web development tool for building fast websites focusing on content.
Let’s initialize a new Astro site:

# create a new project with npm
npm create astro@latest

# create a new project with pnpm
pnpm create astro@latest

# create a new project with yarn
yarn create astro
Enter fullscreen mode Exit fullscreen mode

This will prompt you to enter a project name and select a template. For this tutorial, we’ll use the blog template and TypeScript as the language.

Then, organize your translations within the Astro’s publicDir, in the locales directory. In the example below, we show a simple use case of implementing language sub-paths in Astro using a JSON files to store translations. We will work with three languages, en, fr, and es. In this case, you might have the following locale structure:

public
└── locales
    ├── en
    |   └── translation.json
    └── fr
    |   └── translation.json
    └── es
        └── translation.json
Enter fullscreen mode Exit fullscreen mode

The translation files will have the following structure:

public/locales/en/translation.json:

{
  "nav.home": "Home"`,
  "nav.blog": "Blog",
  "nav.about": "About"
}
Enter fullscreen mode Exit fullscreen mode

public/locales/fr/translation.json:

{
  "nav.home": "Page d'Accueil",
  "nav.blog": "Blogue",
  "nav.about": "À propos de"
}
Enter fullscreen mode Exit fullscreen mode

public/locales/es/translation.json:

{
  "nav.home": "Página Principal",
  "nav.blog": "Blog",
  "nav.about": "Acerca de"
}
Enter fullscreen mode Exit fullscreen mode

It can be either a plain or nested JSON file depending on your needs. The filename should be the same for all languages. The only difference is the language code in the path.

Crowdin CLI Configuration

In Astro, you can incorporate Crowdin CLI in your project to:

  • Automate the process of updating your source files in your Crowdin project
  • Download translations from Crowdin and automatically save them in the correct locations
  • Upload all your existing translations to Crowdin in minutes The easiest way to install the Crowdin CLI is to use npm:
npm install -g @crowdin/cli
Enter fullscreen mode Exit fullscreen mode

Visit the official CLI documentation to explore other installation options.

To configure Crowdin CLI in your project, run the following command:

crowdin init
Enter fullscreen mode Exit fullscreen mode

You’ll be prompted to enter your Crowdin Project ID and your Personal Access Token. It will generate the crowdin.yml file in the root directory of your project.

To set up the Crowdin CLI for your Astro project, you need to add the following configuration to the crowdin.yml file:

"project_id": "project-id"
"api_token": "personal-access-token"

"base_path": "."
"preserve_hierarchy": true
"base_url": "https://api.crowdin.com" # https://{organization-name}.api.crowdin.com for Crowdin Enterprise

"files": [
  {
    "source": "/public/locales/en/translation.json", # Source language file pattern
    "translation": "/public/locales/%two_letters_code%/translation.json"  # Translation files pattern
  }
]
Enter fullscreen mode Exit fullscreen mode

It’s recommended to use environment variables for referencing the token in your crowdin.yml file:

"project_id_env": "CROWDIN_PROJECT_ID"
"api_token_env": "CROWDIN_PERSONAL_TOKEN"
Enter fullscreen mode Exit fullscreen mode

VCS (Git) Integrations

Crowdin provides VCS (version control systems) integrations for different platforms including GitHub, GitLab, Bitbucket, Azure Repos and other platforms.

  • GitHub: supports various GitHub workflows, such as pull request and push notifications, branch updates, and automatic commits.
  • GitLab: allows you to synchronize your source and translation files with your GitLab repository, as well as manage your project languages and track the translation progress.
  • Bitbucket: allow you to automate updating your source and translation files with your Bitbucket repository.
  • Azure Repos: allows you to synchronize your source and translation files with your Azure Repos repository

You can also use the Crowdin GitHub Action to automatically manage and synchronize localization resources with your Crowdin project using GitHub workflows.

Setting Up Language Sub-Paths in Astro

Organizing translations for your website or application to language sub-paths in Astro is easy. It simplifies the management process and guarantees a consistent user experience across your application.

Setting up these sub-paths involves including the “lang” parameter in your Astro routes, making the process straightforward. The sub-paths create distinct paths for each section of your site, each with its translations.

Let’s connect the previously created JSON files with the Astro project using the astro-i18next package.

To use the astro-i18next package, you need to install it first:

# npm
npm install astro-i18next

# yarn
yarn add astro-i18next

# pnpm
pnpm add astro-i18next
Enter fullscreen mode Exit fullscreen mode

After installing the package, you can start using it to internationalize your project. To do this, you need to add astro-i18next to your astro.config.mjs:

import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import sitemap from '@astrojs/sitemap';

import astroI18next from  'astro-i18next';

export default defineConfig({
  site: 'https://example.com',
  integrations: [mdx(), sitemap(), astroI18next()],
});
Enter fullscreen mode Exit fullscreen mode

Configure astro-i18next in your astro-i18next.config.mjs file:

/** @type {import('astro-i18next').AstroI18nextConfig} */
export default {
  defaultLocale: "en",
  locales: ["en", "fr", "es"],
};
Enter fullscreen mode Exit fullscreen mode

Next, we need to use the t() function available in the astro-i18next package to translate the header link titles, for example:

---
import HeaderLink from './HeaderLink.astro';
import { SITE_TITLE } from '../consts';
import i18next, { t } from 'i18next';

const lang = i18next.language;
const base = lang === 'en' ? '' : `/${lang}`;
---

<header>
  <h2>
    {SITE_TITLE}
  </h2>
  <nav>
    <HeaderLink href={`${base}/`}>{ t('nav.home') }</HeaderLink>
    <HeaderLink href={`${base}/blog`}>{ t('nav.blog') }</HeaderLink>
    <HeaderLink href={`${base}/about`}>{ t('nav.about') }</HeaderLink>
    <HeaderLink href="https://twitter.com/astrodotbuild" target="_blank">Twitter</HeaderLink>
    <HeaderLink href="https://github.com/withastro/astro" target="_blank">GitHub</HeaderLink>
  </nav>
</header>
Enter fullscreen mode Exit fullscreen mode

Note that we use the i18next.language variable to get the current language in order to build the base path for header links. The t() function is used to translate the text.

The package also provides a language switcher component that you can use to switch between languages. To use it, you need to import the LanguageSelector component from the astro-i18next package. Let’s add it to the src/components/Footer.astro component:

---
import { LanguageSelector } from 'astro-i18next/components';
---

<footer>
  <LanguageSelector showFlag={true} />
</footer>
Enter fullscreen mode Exit fullscreen mode

Create localized pages using the generate command:

npx astro-i18next generate
Enter fullscreen mode Exit fullscreen mode

You're all set! Now we can run the project and see the results:

npm run dev
Enter fullscreen mode Exit fullscreen mode

You’re all set! Now we can run the project and see the results:
Go to the project in a web browser (http://localhost:3000) and try to change the language 🚀

The localized pages will be available at the following URLs:

Connecting Crowdin in an Astro Context

Connecting Crowdin to Astro is easy using APIs provided by Crowdin. To integrate Crowdin with Astro, follow these steps:

  • Create a project in Crowdin and set up your translation workflow.

  • Connect your repository to Crowdin to sync your source files and translations.

Here’s an example of using Crowdin to manage translations in an Astro website:

  • In Crowdin, create a new project and upload the source files you need to translate.

  • Set up the translation workflows, translation memory, and terminology management.

  • Connect your repository to Crowdin to sync your source files and translations.

  • To switch between languages, use the lang parameter in your Astro routes. For example, when a user visits /es/blog, the API will retrieve the Spanish translations. If the user visits /fr/blog, the API will retrieve the French translations.

i18n Implementation in Astro

Internationalization, or i18n, in Astro, refers to changing a web application to support multiple languages, date and time styles, and number styles. Visit the Astro documentation to learn more about i18n in Astro.

Considerations for Crowdin as a Translation Management System using Astro

There are aspects to consider when working with Crowdin as a TMS with the Astro web framework. These factors may need paying attention to before you can get started with your application:

  • Integration: Ensure that Crowdin integrates seamlessly with the Astro framework.

  • Translation process: Make sure that you have a simple process for handling translation requests, revisions, and approvals.

  • Terminology management: Use Crowdin’s terminology management feature to ensure you use consistent terminology throughout the translation process.

  • Translation memory: Take advantage of Crowdin’s translation memory feature to store and reuse translations for frequently used phrases and sentences.

  • Project management: Use Crowdin’s project management tools to keep track of the translation process, deadlines, and progress.

  • User management: Consider setting up user roles and permissions within Crowdin. This allows you to manage access to the translation project and ensure that the right people have access to the right information.

  • Performance: Test the performance of the integration between Crowdin and Astro to ensure that it performs well in production.

  • Error handling: Handle errors gracefully and log them meaningfully, so you can debug and resolve issues when they arise.

Wrapping Up

By utilizing Astro and Crowdin, you can streamline the localization process, and the result will be a web application accessible to a diverse global audience.
Start a free 14-day trial today to make your company multilingual with Crowdin.

💖 💪 🙅 🚩
yanafeshchuk
yanafeshchuk

Posted on July 12, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Astro Websites Localization and Internalization