npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

next-intlayer

v2.0.13

Published

Internationalisation tool for Next.js applications. Declare your multilingual contant in the same lever than your component. Powered by TypeScript, declaration files.

Downloads

117,797

Readme

Intlayer: Next-Level Content Management in JavaScript

Intlayer is an internationalization library designed specifically for JavaScript developers. It allow the declaration of your content everywhere in your code. It converts declaration of multilingual content into structured dictionaries to integrate easily in your code. Using TypeScript, Intlayer make your development stronger and more efficient.

Example of usage

.
├── ClientComponent
│   ├── index.content.ts
│   └── index.tsx
└── ServerComponent
    ├── index.content.ts
    └── index.tsx
// ./ClientComponent/index.content.ts

import { DeclarationContent, t } from "intlayer";

const clientComponentContent: DeclarationContent = {
  id: "client-component",
  myTranslatedContent: t({
    en: "Hello World",
    fr: "Bonjour le monde",
    es: "Hola Mundo",
  }),
};

export default clientComponentContent;
// ./ClientComponent/index.tsx
"use client";

import { useIntlayer } from "next-intlayer";

export const ClientComponent = () => {
  const { myTranslatedContent } = useIntlayer("client-component");

  return <span>{myTranslatedContent}</span>;
};

Why Choose Intlayer?

  • JavaScript-Powered Content Management: Harness the flexibility of JavaScript to define and manage your content efficiently.
  • Type-Safe Environment: Leverage TypeScript to ensure all your content definitions are precise and error-free.
  • Integrated Content Files: Keep your translations close to their respective components, enhancing maintainability and clarity.
  • Simplified Setup: Get up and running quickly with minimal configuration, especially optimized for Next.js projects.
  • Server Component Support: Perfectly suited for Next.js server components, ensuring smooth server-side rendering.
  • Enhanced Routing: Full support for Next.js app routing, adapting seamlessly to complex application structures.

Getting Started with Intlayer and Next.js

Setting up Intlayer in a Next.js application is straightforward:

Step 1: Install Dependencies

Install the necessary packages using npm:

npm install intlayer next-intlayer
yarn install intlayer next-intlayer
pnpm install intlayer next-intlayer

Step 2: Configure Your Project

Create a config file to configure the languages of your application:

// intlayer.config.ts

import { Locales, type IntlayerConfig } from "intlayer";

const config: IntlayerConfig = {
  internationalization: {
    locales: [
      Locales.ENGLISH,
      Locales.FRENCH,
      Locales.SPANISH,
      // Your other locales
    ],
    defaultLocale: Locales.ENGLISH,
  },
};

export default config;

To see all available parameters, refer to the configuration documentation here.

Step 3: Integrate Intlayer in Your Next.js Configuration

Configure your Next.js setup to use Intlayer:

// next.config.mjs
import { withIntlayer } from "next-intlayer/server";

/** @type {import('next').NextConfig} */
const nextConfig = {};

export default withIntlayer(nextConfig);

Step 4: Configure Middleware for Locale Detection

Set up middleware to detect the user's preferred locale:

// src/middleware.ts
export { intlayerMiddleware as middleware } from "next-intlayer/middleware";

export const config = {
  matcher: "/((?!api|static|.*\\..*|_next).*)",
};

Step 5: Define Dynamic Locale Routes

Implement dynamic routing for localized content:

Change src/app/page.ts to src/app/[locale]/page.ts

Then, implement the generateStaticParams function in your application Layout.

// src/app/layout.tsx

import type { ReactNode } from "react";
import "./globals.css";

export { generateStaticParams } from "next-intlayer"; // Line to insert

const RootLayout = ({
  children,
}: Readonly<{
  children: ReactNode;
}>) => children;

export default RootLayout;

Then add a new layout in your [locale] directory:

// src/app/[locale]/layout.tsx

import { NextLayoutIntlayer } from "next-intlayer";
import { Inter } from "next/font/google";

const inter = Inter({ subsets: ["latin"] });

const LocaleLayout: NextLayoutIntlayer = ({ children, params: { locale } }) => (
  <html lang={locale}>
    <body className={inter.className}>{children}</body>
  </html>
);

export default LocaleLayout;

Step 6: Declare Your Content

Create and manage your content dictionaries:

// src/app/[locale]/page.content.ts
import { t, type DeclarationContent } from "intlayer";

const pageContent: DeclarationContent = {
  id: "page",
  getStarted: {
    main: t({
      en: "Get started by editing",
      fr: "Commencez par éditer",
      es: "Comience por editar",
    }),
    pageLink: "src/app/page.tsx",
  },
};

export default pageContent;

Note: If your content file includes TSX code, you should consider importing import React from "react"; in your content file.

See how to declare your Intlayer declaration files.

Step 7: Utilize Content in Your Code

Access your content dictionaries throughout your application:

// src/app/[locale]/page.ts

import { ClientComponentExample } from "@component/components/ClientComponentExample";
import { LocaleSwitcher } from "@component/components/LangSwitcherDropDown";
import { NestedServerComponentExample } from "@component/components/NestedServerComponentExample";
import { ServerComponentExample } from "@component/components/ServerComponentExample";
import { type NextPageIntlayer, IntlayerClientProvider } from "next-intlayer";
import { IntlayerServerProvider, useIntlayer } from "next-intlayer/server";

const Page: NextPageIntlayer = ({ params: { locale } }) => {
  const content = useIntlayer("page", locale);

  return (
    <>
      <p>
        {content.getStarted.main}
        <code>{content.getStarted.pageLink}</code>
      </p>
      {/**
       *   IntlayerServerProvider is used to provide the locale to the server children
       *   Don't work if set in the layout
       */}
      <IntlayerServerProvider locale={locale}>
        <ServerComponentExample />
      </IntlayerServerProvider>
      {/**
       *   IntlayerClientProvider is used to provide the locale to the client children
       *   Can be set in any parent component, including the layout
       */}
      <IntlayerClientProvider locale={locale}>
        <ClientComponentExample />
      </IntlayerClientProvider>
    </>
  );
};

export default Page;
// src/components/ClientComponentExample.tsx

"use client";

import { useIntlayer } from "next-intlayer";

export const ClientComponentExample = () => {
  const content = useIntlayer("client-component-example"); // Create related content declaration

  return (
    <div>
      <h2>{content.title} </h2>
      <p>{content.content}</p>
    </div>
  );
};
// src/components/ServerComponentExample.tsx

import { useIntlayer } from "next-intlayer/server";

export const ServerComponentExample = () => {
  const content = useIntlayer("server-component-example"); // Create related content declaration

  return (
    <div>
      <h2>{content.title} </h2>
      <p>{content.content}</p>
    </div>
  );
};

Note: If you want to use your content in a string attribute, such as alt, title, href, aria-label, etc., you must call the value of the function, like:

<img src={content.image.src.value} alt={content.image.value} />

For more detailed usage of intlayer into Client, or Server component, see the nextJS example here.

(Optional) Step 8: Internationalization of your metadata

In the case you want to internationalize your metadata, such as the title of your page, you can use the generateMetadata function provided by NextJS. Inside the function use the getTranslationContent function to translate your metadata.

// src/app/[locale]/metadata.ts

import { type IConfigLocales, getTranslationContent } from 'intlayer';
import type { Metadata } from 'next';
import type { LocalParams } from 'next-intlayer';

export const generateMetadata = ({
  params: { locale },
}: LocalParams): Metadata => {
  const t = <T>(content: IConfigLocales<T>) =>
    getTranslationContent(content, locale);

  return {
    title: t<string>({
      en: 'My title',
      fr: 'Mon titre',
      es: 'Mi título',
    }),
    description: t({
      en: 'My description',
      fr: 'Ma description',
      es: 'Mi descripción',
    }),

};

(Optional) Step 9: Change the language of your content

To change the language of your content, you can use the setLocale function provided by the useLocale hook. This function allows you to set the locale of the application and update the content accordingly.

import { Locales } from "intlayer";
import { useLocale } from "next-intlayer";

const MyComponent = () => {
  const { setLocale } = useLocale();

  return (
    <button onClick={() => setLocale(Locales.English)}>Change Language</button>
  );
};

Configure TypeScript

Intlayer use module augmentation to get benefits of TypeScript and make your codebase stronger.

alt text

alt text

Ensure your TypeScript configuration includes the autogenerated types.

// tsconfig.json

{
  // your custom config
  include: [
    "src",
    "types", // <- Include the auto generated types
  ],
}