NextGlobeGen

website·Indexed 32 days ago

https://next-globe-gen.dev/

An internationalization (i18n) library for Next.js designed to deliver content in multiple languages with SEO-optimized, localized URLs. It provides a CLI for generation, a Next.js plugin, and a suite of tools including createTranslator, useLocale, and specialized Link and Form components.

Tokens
13.2K
Snippets
81
Records
92
Agent score
64%

What's inside NextGlobeGen

  1. Overview of NextGlobeGen i18n for Next.js

    NextGlobeGen is a TypeScript-first internationalization (i18n) library designed specifically for the Next.js App Router. It uses generative programming to automatically create localized routes and type-safe APIs at build time, eliminating runtime overhead. Key capabilities include SEO-optimized localized URLs, automatic key extraction, and support for both Server and Client Components.
  2. NextGlobeGen Core Features Overview

    NextGlobeGen offers several developer-experience (DX) features for Next.js i18n:

    • TypeScript Support: Automatic typing for routes, locales, and message arguments with full autocomplete.
    • Automatic Key Extraction: Translation keys are automatically discovered from source code to keep message files in sync.
    • Rich Text Messages: Support for ICU MessageFormat with interpolation patterns for dynamic translations.
    • Localized Pathnames: Ability to translate URL segments for SEO optimization.
    • Universal APIs: Hooks and components that work across both Server and Client Components.
    • Smart Locale Detection: Built-in proxy for locale detection, automatic redirects, and SEO-friendly alternate links.
  3. Understand NextGlobeGen's generative routing architecture

    NextGlobeGen uses generative programming to automatically create localized routes at build time. Instead of manually creating [locale] route groups, developers write routes once in src/_app/, and the plugin generates the corresponding locale-specific variants in src/app/(i18n)/ along with the necessary TypeScript types.
    // Developer writes: src/_app/page.tsx (once)
    // Plugin generates: src/app/(i18n)/en/page.tsx
    //                   src/app/(i18n)/fi/page.tsx
  4. Configure domain-based routing

    Instead of prefix-based routing (e.g., /en/about), you can serve locales from different domains. Use the domains option in i18n.config.ts instead of locales and defaultLocale.

    Requirements:

    1. Middleware: You must export the NextGlobeGen middleware in src/middleware.ts for redirects to work.
    2. DNS: Each domain must point to the application.
    // i18n.config.ts
    import type { Config } from "next-globe-gen";
    
    const config: Config = {
      domains: [
        {
          domain: "example.com",
          locales: ["en"],
          defaultLocale: "en",
        },
        {
          domain: "example.fi",
          locales: ["fi"],
          defaultLocale: "fi",
        },
        {
          domain: "example.de",
          locales: ["de", "de-AT"],
          defaultLocale: "de",
          prefixDefaultLocale: true, // Serve default from /de instead of /
        },
      ],
    };
    
    export default config;
    
    // src/middleware.ts
    export { middleware } from "next-globe-gen/middleware";
    export const config = {
      matcher: ["/((?!_next|.*\\.).*)"],
    };
  5. Understand NextGlobeGen routing directory structure

    NextGlobeGen uses a special src/_app directory for application routes. All Next.js file-system based routing rules and specific routing files work in src/_app exactly as they do in the standard src/app directory. Localized routes are automatically generated into src/app/(i18n) based on the contents of src/_app.

    Important:

    • Do not modify the src/app/(i18n) directory.
    • Non-localized routes (e.g., api routes) and static files (e.g., favicon.ico) should still be placed in the root of the src/app directory.
  6. Use internationalization utilities in Async Server Components

    Since hooks cannot be called inside async server components or the generateMetadata function, next-globe-gen provides get-prefixed aliases for its hooks. Use these aliases to access locale, schema, translations, and hrefs on the server side.
    // Use these instead of hooks in Server Components:
    import { getLocale, getSchema, getTranslations, getHref } from 'next-globe-gen';
  7. Translate static route segments (pathnames)

    To translate static route segments for SEO, create an i18n.ts file within the specific route segment directory in src/_app.

    Dynamic parameters cannot be translated via i18n.ts; they must be handled manually by providing translated parameters to the Link component.

    // src/_app/dashboard/i18n.ts
    const segmentTranslations = {
      en: "dashboard", // If omitted, the directory name is used
      fi: "hallintapaneeli",
    };
    
    export default segmentTranslations;
  8. Create localized Markdown (MDX) pages

    To use localized MDX pages, first configure Next.js to process MDX. Then, create files using the page.<locale>.mdx convention within the route segment directory in src/_app.
    // src/_app/markdown/page.en.mdx
    export const metadata = { title: "Markdown page" };
    
    # Markdown page
    This content is shown on `/en/markdown` path.
  9. Implement rich text formatting in NextGlobeGen translations

    NextGlobeGen supports advanced translation formatting to handle dynamic content. You can use the ICU message format for handling plurals, dates, and numbers, and embed React components directly within your translation strings to achieve rich text formatting.
  10. Set up localized routing with the _app directory

    NextGlobeGen uses a special _app directory for localized routes. Move your file-system based routing files from the standard app directory into the _app directory.

    • Localized Routes: Create and modify all routes that need translation inside _app.
    • Static Assets: Root-level files like favicon.ico should remain in the standard app directory.
    • Generated Files: The plugin automatically generates the actual routes in src/app/(i18n). Do not modify these generated files manually.
    // src/_app/layout.tsx
    import { Metadata } from "next";
    import { Link, useLocale, useTranslations } from "next-globe-gen";
    import { ReactNode } from "react";
    import LanguageSwitcher from "./LanguageSwitcher";
    
    export const metadata: Metadata = {
      // metadataBase is required for language alternates to work
      metadataBase: new URL("https://example.com"),
      title: { template: "%s | NextGlobeGen", default: "NextGlobeGen" },
    };
    
    export default function RootLayout({ children }: { children: ReactNode }) {
      const locale = useLocale();
      const t = useTranslations();
      return (
        <html lang={locale}>
          <body>
            <header>
              <LanguageSwitcher />
              <nav>
                <ul>
                  <li><Link href="/">{t("title")}</Link></li>
                  <li><Link href="/dashboard">{t("dashboard.title")}</Link></li>
                </ul>
              </nav>
            </header>
            <main>{children}</main>
          </body>
        </html>
      );
    }
  11. Extract translation keys using NextGlobeGen

    NextGlobeGen automatically scans source files for translator function calls (useTranslations, getTranslations, createTranslator) to extract translation keys. Extracted keys are added to message files. To prevent dynamic keys (keys using variables like t(keyVar)) from being pruned during this process, they must be added to the whitelistedKeys configuration.
  12. Use NextGlobeGen components for locale-aware routing

    Standard Next.js components like next/link and next/form do not handle localized routing automatically. To ensure links and forms are locale-aware, import the corresponding versions from next-globe-gen.
    // Replace native Next.js imports with NextGlobeGen versions
    import { Link, Form } from "next-globe-gen";
    
    // Also replace these from 'next/navigation' or 'next/cache':
    // - redirect, permanentRedirect
    // - revalidatePath