0
0
NextJSframework~5 mins

Server component translations in NextJS

Choose your learning style9 modes available
Introduction

Server component translations let you show text in different languages directly from the server. This helps your app speak your user's language without extra work on the browser.

You want to display page content in multiple languages based on user preference.
You want to load translations once on the server to improve performance.
You want to keep your app SEO-friendly by rendering translated content on the server.
You want to avoid sending unnecessary translation code to the browser.
You want to use Next.js server components to handle translations cleanly.
Syntax
NextJS
import { useTranslations } from 'next-intl';

export default function Page({ params }) {
  const t = useTranslations('Namespace');

  return (
    <main>
      <h1>{t('title')}</h1>
      <p>{t('description')}</p>
    </main>
  );
}

useTranslations is a hook that fetches translation strings for a given namespace.

This code runs on the server, so translations are loaded before sending HTML to the browser.

Examples
Load translations from the 'Home' namespace and show the 'welcome' text.
NextJS
const t = useTranslations('Home');

return <h1>{t('welcome')}</h1>;
Use a common namespace for shared words like buttons.
NextJS
const t = useTranslations('Common');

return <button>{t('submit')}</button>;
Define which locales your app supports for static generation.
NextJS
export async function generateStaticParams() {
  return [
    { locale: 'en' },
    { locale: 'fr' }
  ];
}
Sample Program

This server component loads translations from the 'Greeting' namespace. It shows a hello message and a welcome message in the user's language. The app supports English and Spanish locales.

NextJS
import { useTranslations } from 'next-intl';

export default function Greeting({ params }) {
  const t = useTranslations('Greeting');

  return (
    <section>
      <h2>{t('hello')}</h2>
      <p>{t('welcomeMessage')}</p>
    </section>
  );
}

export async function generateStaticParams() {
  return [
    { locale: 'en' },
    { locale: 'es' }
  ];
}
OutputSuccess
Important Notes

Make sure your translation files are organized by locale and namespace.

Server components do not run in the browser, so translation hooks here fetch data on the server.

Use generateStaticParams to tell Next.js which languages to build pages for.

Summary

Server component translations let you show text in different languages from the server.

This improves performance and SEO by sending translated HTML directly to the browser.

Use useTranslations hook inside server components to get translated strings.