astro-i18n-aut

repository·main·Indexed 41 days ago

https://github.com/jlarmstrongiv/astro-i18n-aut

An internationalization integration for Astro (v0.8.1) that automates the creation of localized routes for .astro pages without template duplication. It provides utilities for locale detection, URL generation, and sitemap filtering, and is designed to be adapter and UI framework agnostic.

Tokens
4.4K
Snippets
19
Records
23
Agent score
52%

What's inside astro-i18n-aut

  1. Using Markdown with Content Collections for i18n

    main

    Because .md and .mdx files cannot be directly translated by the integration, you should use Astro Content Collections to manage translated Markdown content.

    Organize your content by language subdirectories within your collection. Then, use .astro files in your pages/ directory to render the content based on the detected locale.

    Recommended Folder Structure:

    .
    └── astro-project/
        └── src/
            ├── pages/
            │   └── blog/
            │       ├── index.astro
            │       └── [id].astro
            └── content/
                └── blog/
                    ├── en/
                    │   ├── post-1.md
                    │   └── post-2.md
                    ├── es/
                    │   ├── post-1.md
                    │   └── post-2.md
                    └── fr/
                        ├── post-1.md
                        └── post-2.md
  2. Configure the astro-i18n-aut integration

    main

    To configure the integration, import i18n and filterSitemapByDefaultLocale from astro-i18n-aut/integration in your astro.config.ts. You must define a locales record and a defaultLocale (which must be a key in the locales record).

    If you are using @astrojs/sitemap, it is recommended to use filterSitemapByDefaultLocale to ensure the sitemap is compatible with the integration's routing logic.

    import { defineConfig } from "astro/config";
    import { i18n, filterSitemapByDefaultLocale } from "astro-i18n-aut/integration";
    import sitemap from "@astrojs/sitemap";
    
    const defaultLocale = "en";
    const locales = {
      en: "en-US", // the `defaultLocale` value must present in `locales` keys
      es: "es-ES",
      fr: "fr-CA",
    };
    
    export default defineConfig({
      site: "https://example.com/",
      trailingSlash: "always",
      build: {
        format: "directory",
      },
      integrations: [
        i18n({
          locales,
          defaultLocale,
        }),
        sitemap({
          i18n: {
            locales,
            defaultLocale,
          },
          filter: filterSitemapByDefaultLocale({ defaultLocale }),
        }),
      ],
    });
  3. Configure integration options for astro-i18n-aut

    main

    The i18n() integration accepts the following options:

    • locales: A record of all language locales.
    • defaultLocale: The default language locale. The value must be present in the locales keys.
    • redirectDefaultLocale: Determines whether the default locale path (e.g., /en/about/) redirects to the root path (e.g., /about/). Defaults to 308 redirect behavior.
    • include: Glob pattern(s) to include in translation. Default is ["pages/**/*"].
    • exclude: Glob pattern(s) to exclude from translation. Default is ["pages/api/**/*"].
  4. Detect the current locale in .astro pages

    main

    Since the integration re-runs the Astro frontmatter for every translated page, you must detect the current locale using the getLocale function and the Astro.url object. This allows you to conditionally render content based on the active language.

    ---
    import { getLocale } from "astro-i18n-aut";
    import Layout from "../layouts/Layout.astro";
    
    const locale = getLocale(Astro.url);
    
    let title: string;
    switch (locale) {
      case "es":
        title = "¡Hola Mundo!";
        break;
      case "fr":
        title = "Bonjour Monde!";
        break;
      default:
        title = "Hello World!";
    }
    ---
    
    <Layout title={title}>
      <h1>{title}</h1>
    </Layout>
  5. Configure UserI18nConfig for astro-i18n-aut

    main

    The UserI18nConfig interface defines the primary configuration options for the astro-i18n-aut integration. You must provide locales and defaultLocale, while other options are optional and have default values.

    Configuration Options

    OptionTypeDefaultDescription
    localesRecord<string, string>RequiredA mapping of language keys to their full locale strings (e.g., { en: 'en-US' }). The defaultLocale key must exist in this object.
    defaultLocalestringRequiredThe key in locales representing the default language.
    includestring | string[]['pages/**/*']Glob pattern(s) to include for i18n processing.
    excludestring | string[]['pages/api/**/*']Glob pattern(s) to exclude from i18n processing.
    redirectDefaultLocaleboolean | ValidRedirectStatus308If true or a status code (like 302 or 308), URLs containing the defaultLocale (e.g., /en/about) will redirect to the version without the locale (e.g., /about).
    const locales = {
      en: "en-US", // the `defaultLocale` value must present in `locales` keys
      es: "es-ES",
      fr: "fr-CA",
    };
    
    // Example configuration object
    const config: UserI18nConfig = {
      locales,
      defaultLocale: "en",
      redirectDefaultLocale: 308,
    };
  6. Supported and unsupported page file types

    main

    The integration only supports translating .astro files.

    Supported:

    • ✅ .astro

    Unsupported (must be excluded via glob patterns):

    • ❌ .md
    • ❌ .mdx
    • ❌ .html
    • ❌ .js / .ts (endpoints)

    To exclude unsupported files, update the exclude option in your configuration. For example, to exclude Markdown files and API endpoints:

    exclude: ["pages/api/**/*", "pages/**/*.md"]

    Note: The standard Astro feature of prefixing files with an underscore (_) to exclude them from routing is not supported by this integration. You must use the exclude glob pattern instead (e.g., ["pages/api/**/*", "pages/**/_*"]).

  7. Configure sitemap filtering for default locales

    main

    The filterSitemapByDefaultLocale function allows you to control whether the sitemap includes pages for the default locale. This is useful for SEO strategies where you might want to exclude or include specific language versions in your sitemap generation.

    import { filterSitemapByDefaultLocale } from 'astro-i18n-aut';
    
    // Usage depends on the specific integration implementation
  8. Install and use the astro-i18n-aut integration

    main

    The primary entrypoint for the integration is the i18n object (also available as the default export). You use this to add the i18n capabilities to your Astro configuration.

    To use it, import i18n from astro-i18n-aut and include it in the integrations array of your astro.config.mjs file.

    import { i18n } from 'astro-i18n-aut';
    import { defineConfig } from 'astro/config';
    
    export default defineConfig({
      integrations: [i18n()],
    });
  9. Use edge runtime URL and locale utilities

    main

    The edge runtime provides utilities for manipulating URLs and identifying locales in a way that is compatible with edge environments.

    Key functions include:

    • getLocale(): Retrieves the current locale.
    • getLocaleUrl(url, locale): Generates a locale-prefixed URL.
    • getLocaleUrlPrefix(locale): Returns the URL prefix for a specific locale.
    • getAllLocaleUrls(): Returns all available locale URLs.
    • getUrlWithoutLocale(url): Removes the locale prefix from a URL.
    • getCollectionParamsSlug(): Retrieves slug parameters for collections.
    • resolveTrailingSlash(url): Handles trailing slash resolution.
    • filterCollectionByDefaultLocale(collection): Filters collections based on the default locale.
    import { getLocale, getLocaleUrl } from 'astro-i18n-aut/edge';
    
    const currentLocale = getLocale();
    const localizedUrl = getLocaleUrl('/about', currentLocale);
  10. Import configuration constants from the edge runtime

    main

    The edge runtime entrypoint exports several core configuration constants used for managing i18n settings. These include defaultLocale, locales, localeKeys, trailingSlash, and BASE_URL.

    import { 
      defaultLocale, 
      locales, 
      localeKeys, 
      trailingSlash, 
      BASE_URL 
    } from 'astro-i18n-aut/edge';
  11. Retrieve all locale-specific URLs with getAllLocaleUrls

    main

    The getAllLocaleUrls function takes a given URL (as a string or a URL object) and returns a mapping of all available locales to their corresponding URLs. This is useful for generating language switchers or link lists that cover every supported language in the project.

    Key behaviors:

    • It automatically handles the baseUrl, defaultLocale, and localeKeys configured in your project.
    • It resolves trailing slashes according to your project configuration.
    • It correctly identifies if a URL already contains a locale prefix or if it is a base path.
    • It strips .html extensions from the input path to ensure clean URL generation.
    // Example 1: Inputting a path that already has a locale
    getAllLocaleUrls("/es/about") 
    // Returns: { en: "/about", "es": "/es/about" }
    
    // Example 2: Inputting a base path
    getAllLocaleUrls("/about") 
    // Returns: { en: "/about", "es": "/es/about" }