Storyblok
Search Storyblok's Documentation
  1. Internationalization in Astro

Internationalization in Astro

Learn how to create a basic implementation of field-level translation in an Astro project.

Setup

Copy the reference space, providing the intended structure to follow this guide. Make sure to update the access token.

Alternatively, go to Settings > Internationalization > Languages and add es (Spanish).

  • In the article content type block schema, set the title and content fields as translatable.
  • Go to each article, select the Spanish language, and provide translated content. You can also use AI Translations.

Learn more in the internationalization concept.

Use the language parameter

Update the src/pages/[...slug].astro file to support language paths.

src/pages/[...slug].astro
---
import { useStoryblokApi } from '@storyblok/astro';
import StoryblokComponent from '@storyblok/astro/StoryblokComponent.astro';
import Layout from '../layouts/Layout.astro';

const slug = Astro.params.slug?.split('/') ?? [];

const availableLanguages = ['es'];
const language = availableLanguages.includes(slug[0]) ? slug[0] : undefined;

if (language) {
	slug.shift();
}

const storyblokApi = useStoryblokApi();
const { data } = await storyblokApi.get(
	`cdn/stories/${slug && slug.length > 0 ? slug.join('/') : 'home'}`,
	{
		version: 'draft',
		resolve_relations: 'featured-articles.articles',
		language,
	},
);

const story = data.story;
---

<Layout>
	<StoryblokComponent blok={story.content} />
</Layout>

First, an array with all language codes configured in the space is defined.

The language code is the first part of the full_slug of each language-specific story version, and the Visual Editor is configured to request that path. For example, the Spanish version of articles/example-article would be es/articles/example-article.

In the example code, if the first array element of the slug is included in the languages array, it is set as the language parameter for the API request. Moreover, the first array element is subsequently removed so that the slug used for the API request does not contain any language-specific information. The language is exclusively handled via the language parameter.

Note that this approach works for all stories except the home story, if it is defined as the root. Internationalization is highly implementation-specific, and how to handle the home story as well as other aspects is dependent on the exact project requirements. In Astro, you may, for example, want to create a static route pages/es/index.vue that takes precedence over the dynamic route pages/[…slug].astro. This static route can be configured to fetch the home story in Spanish, rendering it when https://localhost/es is visited.