Nextjs Localization Guide for Building Multilingual Sites

Category
Next.js
Reading Time
0
 min
Date
September 15, 2024

Why Multilingual Sites Matter

Multilingual websites expand your audience and boost engagement. Localizing your site helps diverse audiences connect with your content, regardless of their language or culture. This improves user experience and keeps visitors on your site longer.

Why go multilingual? Consider these benefits:

  • Global Reach: Reach new markets and expand your potential customer base.
  • Better Engagement: Speaking users' languages creates personal connections, leading to longer visits and better interactions.
  • Increase Sales: International markets offer more sales opportunities, boosting your revenue.
  • Better Search Rankings: Localized content improves search rankings, making your site easier to find globally.
  • Gain Trust: Multilingual content shows respect for diversity, building trust with international audiences.

Multilingual sites do more than translate content—they make users feel understood. This approach expands your market and builds user loyalty and satisfaction. Embracing multilingual capabilities drives your brand's growth and success.

Getting Started with Next.js

Next.js is a powerhouse for building high-performance web applications. It’s popular among developers for its robust capabilities and user-friendly features. With server-side rendering and static site generation, Next.js ensures fast load times and improved SEO. This makes it a top choice for delivering a seamless user experience.

Key features make Next.js stand out. Here’s why developers love it:

  • Server-Side Rendering (SSR): Offers better performance and SEO by rendering pages on the server.
  • Static Site Generation (SSG): Provides pre-rendered pages, boosting speed and reliability.
  • Internationalized Routing: Simplifies the process of building multilingual sites, making it easier to reach global audiences.
  • Automatic Code Splitting: Loads only necessary code, enhancing page load speed.
  • Dynamic Routing: Supports complex routing patterns, essential for growing applications.

Developers looking to create multilingual sites find Next.js particularly appealing. Its internationalized routing feature allows you to manage languages effortlessly. Combine that with its fast performance and SEO benefits, and you've got a framework that’s tailor-made for global reach.

Next.js is not just about features. It’s about creating applications that scale well and perform excellently across the board. For those interested in a deeper comparison between Next.js and React, our detailed guide on choosing between Next.js and React for your project can provide valuable insights. With strong community support and extensive documentation, it’s a reliable choice for modern web development.

Setting Up a Next.js Project

Ready to set up your Next.js project? Start by creating a new app. Use the command below to get things rolling:

npx create-next-app@latest

Choose your preferred options like TypeScript, ESLint, and Tailwind CSS during setup. This kickstarts your development with a solid foundation.

Next, configure your project for localization. Begin by setting up your next.config.js file. Here, you'll define your internationalization settings. It's essential to specify the locales your app will support. This ensures Next.js knows how to handle multiple languages efficiently.

For the translation part, libraries like next-i18next or next-intl come in handy. They simplify the process of managing translations across your app. You'll want to create a folder dedicated to your translation files. A common approach is to use a directory like src/app/dictionaries.

Inside this folder, create JSON files for each language you plan to support. For example, you might have en.json for English and es.json for Spanish. These files will store your translation keys and corresponding text. Organizing your files logically makes managing translations easier as your app grows. This setup not only prepares your app for multilingual support but also aligns perfectly with your goal of reaching a global audience.

For additional insights on setting up a scalable project structure in Next.js 13, you might find our guide on building large-scale applications with Next.js particularly useful. This guide covers best practices for maintaining a solid folder structure, efficient environment setup, and leveraging Next.js features for optimization.

a computer screen with a bunch of text on it

Creating Localization Files

Creating localization files is a key step in developing a multilingual site with Next.js. These files store translations for different languages, making it easy to switch between them based on user preference or location. Let's see how you can set this up.

Start by creating a directory for your localization files, often named locales or dictionaries. Inside this directory, create JSON files for each language you want to support. These files will contain key-value pairs where the key is used in your code, and the value is the translated text.

Here's a basic example of how your en.json file might look:

{
"welcomeMessage": "Welcome to our site!",
"contactUs": "Contact Us",
"about": "About Us"
}

For a Spanish version, create an es.json file:

{
"welcomeMessage": "¡Bienvenido a nuestro sitio!",
"contactUs": "Contáctenos",
"about": "Sobre nosotros"
}

Similarly, you can create files like fr.json for French, de.json for German, and ar.json for Arabic. Here’s a snippet for the French file to illustrate:

{
"welcomeMessage": "Bienvenue sur notre site!",
"contactUs": "Contactez-nous",
"about": "À propos de nous"
}

These files are utilized within your Next.js app to display content in the selected language. By using libraries like next-i18next, you can easily manage these translations and ensure a smooth multilingual experience for your users. This setup is vital for reaching a broader audience and enhancing user engagement through localization. For more information on handling common challenges in MVP development with Next.js, including performance optimization and data fetching complexities, check out our detailed guide on navigating common challenges in Next.js MVP development.

Using Next-I18next for Translations

Setting up translations in a Next.js project with next-i18next is straightforward. Start by installing the necessary packages. You'll need both next-i18next and react-i18next. Run this command:

npm install next-i18next react-i18next

Next, configure next-i18next. Create a next-i18next.config.js file in your project root. Here's a basic setup:

module.exports = {
i18n: {
locales: ['en', 'es', 'fr'],
defaultLocale: 'en',
},
};

This tells Next.js which languages you want to support and sets a default language.

Modify your next.config.js to include this configuration:

const { i18n } = require('./next-i18next.config');

module.exports = {
i18n,
};

Now, set up your translation files. Create a /public/locales directory. Inside this, make subfolders for each locale, like /en, /es, and /fr. Within each, create JSON files for your translations:

Example public/locales/en/common.json:

{
"welcome": "Welcome",
"goodbye": "Goodbye"
}

For Spanish, public/locales/es/common.json could look like:

{
"welcome": "Bienvenido",
"goodbye": "Adiós"
}

To use these translations in a component, leverage the useTranslation hook from next-i18next. Import it and call it within your component:

import { useTranslation } from 'next-i18next';

const MyComponent = () => {
const { t } = useTranslation('common');

return (
<div>
<h1>{t('welcome')}</h1>
</div>
);
};

This setup provides a seamless way to manage and display translations in your Next.js app, enhancing your site's global reach. For further insights on optimizing your Next.js applications, consider exploring our guide on building large-scale applications with Next.js, which covers best practices for performance and scalability.

Fetching Data Based on Locale

Fetching data based on a user's locale personalizes the experience. You can do this with getServerSideProps in Next.js. This function fetches data server-side, providing content based on language preferences.

Set up getServerSideProps in your page component. This function runs at request time, letting you access the incoming request's context. You can detect the user's locale and fetch the appropriate data here.

Here's how to set it up:

export async function getServerSideProps(context) {
const { locale } = context;

// Fetch data based on the locale
const response = await fetch(`https://api.example.com/data?lang=${locale}`);
const data = await response.json();

return {
props: { data }, // Pass data to the page component
};
}

const MyPage = ({ data }) => {
return (
<div>
<h1>{data.title}</h1>
<p>{data.description}</p>
</div>
);
};

export default MyPage;

This code uses the context parameter to detect the locale. The fetch call retrieves data specific to that locale. This shows users content in their language and region, improving their experience.

For more details on optimizing your application, you might find our article on building large-scale applications with Next.js particularly useful. It covers best practices like maintaining a solid folder structure, efficient environment setup, and leveraging Next.js features for optimization.

Serving locale-specific content connects you with a global audience and addresses their needs. It boosts user satisfaction and helps your site succeed internationally. Additionally, understanding static site generation in Next.js can further enhance your web development by converting websites into pre-rendered static HTML files for faster loading, improved security, and better SEO performance.

a computer screen with a bunch of lines on it

Handling Localized Routes

Handling localized routes in Next.js is straightforward and powerful. You can dynamically manage these routes, ensuring users experience the site in their preferred language. Start by using Next.js's built-in internationalized routing. This makes it easy to manage different language paths and serve the right content. For more insights on optimizing your Next.js applications, you might find our article on building large-scale applications with Next.js particularly useful.

Make the locale available to your components using the useRouter hook from Next.js. This hook lets you access the current locale and other routing details. Here's a quick example:

import { useRouter } from 'next/router';

const MyComponent = () => {
const { locale } = useRouter();

return <p>Current language: {locale}</p>;
};

For dynamic links, Next.js’s <Link> component is your go-to tool. Using <Link> helps maintain correct routing and ensures all paths reflect the user's language choice. It's crucial to use the pathname and query properties within <Link> to handle locales properly. Here's how you might set it up:

import Link from 'next/link';

const MyPage = () => {
return (
<div>
<Link href={{ pathname: '/', query: { lang: 'en' } }}>
<a>English</a>
</Link>
<Link href={{ pathname: '/', query: { lang: 'es' } }}>
<a>Español</a>
</Link>
</div>
);
};

This setup keeps links dynamic and aligned with the user's language preference. It ensures users can navigate seamlessly across different localized pages. By making locales available to components and using <Link> effectively, your app remains user-friendly and accessible to a global audience. Additionally, understanding the benefits of using Next.js for web app development can further enhance your project's performance and scalability.

Static Generation of Localized Pages

Static generation with Next.js is a powerful way to deliver fast, SEO-friendly pages. When dealing with multilingual sites, you can use getStaticPaths and getStaticProps to create localized pages effortlessly. These functions help generate paths for each locale and fetch the necessary localized content.

Start by defining your paths with getStaticPaths. This function tells Next.js which locales and routes to generate at build time. Here’s a quick setup:

export async function getStaticPaths() {
const paths = [
{ params: { slug: 'home' }, locale: 'en' },
{ params: { slug: 'home' }, locale: 'es' },
{ params: { slug: 'home' }, locale: 'fr' },
];

return { paths, fallback: false };
}

In this example, paths are created for 'home' in English, Spanish, and French. This ensures each version of the page is pre-rendered and ready to go.

Next, use getStaticProps to fetch localized content. This function gets the data needed for each page based on the locale:

export async function getStaticProps({ params, locale }) {
const res = await fetch(`https://api.example.com/pages/${params.slug}?lang=${locale}`);
const pageData = await res.json();

return {
props: { pageData },
};
}

Here, getStaticProps fetches page data specific to each locale using the locale parameter. This way, your page displays the correct language content without delay.

By combining getStaticPaths and getStaticProps, you effectively manage and serve localized content. This approach optimizes load times and improves the user experience by showing the right content for each language. It’s a crucial step for building scalable, multilingual applications with Next.js. For a deeper understanding of how to leverage Static Site Generation in your projects, you can explore our detailed guide on Static Site Generation in Next.js.

Making the Language Switcher Functional

Creating a functional language switcher in a Next.js app involves using the useRouter hook for seamless navigation between different locales. This setup allows users to switch languages without altering the current page's pathname or query parameters. It's all about providing a smooth transition that maintains the user’s context.

Start by importing the useRouter hook from next/router. This hook gives you access to the router instance, which is key to programmatically changing locales. Here’s a basic setup for a language switcher component:

import { useRouter } from 'next/router';

const LanguageSwitcher = () => {
const router = useRouter();
const { pathname, query, asPath } = router;

const changeLanguage = (locale) => {
router.push({ pathname, query }, asPath, { locale });
};

return (
<div>
<button onClick={() => changeLanguage('en')}>English</button>
<button onClick={() => changeLanguage('es')}>Español</button>
<button onClick={() => changeLanguage('fr')}>Français</button>
</div>
);
};

This component uses router.push to navigate to the same page in a different language. The current pathname and query are maintained, ensuring a seamless switch. The asPath parameter helps preserve URL structure, providing continuity in user navigation.

For a smooth user experience, ensure that your application handles language-specific data correctly. Preload necessary assets and translations to avoid delays. This proactive approach keeps the app responsive and user-friendly as it adapts to different languages.

If you're interested in more advanced Next.js functionalities, such as server-side rendering (SSR) and static site generation (SSG), you might find our article on building large-scale applications with Next.js particularly useful. It covers best practices and optimization techniques to enhance performance and scalability.

A well-implemented language switcher enhances accessibility and global reach, making your Next.js app more inclusive and versatile.

black flat screen computer monitor

Key Takeaways for Next.js Localization

Localization with Next.js expands your website's global reach. It boosts engagement and user satisfaction. To create a multilingual site, focus on project setup, translation management, and routing.

Define locales in next.config.js for smooth handling of multiple languages. Use libraries like next-i18next to manage translations in organized directories.

Create localization files to store translations. These files enable easy language switching based on user preferences. Handle routes that respect language preferences. Use Next.js's built-in internationalized routing and dynamic links for path management.

Use getServerSideProps or getStaticProps to fetch data based on locale. This serves content in the user's preferred language. Add a language switcher for smooth transitions between languages.

Next.js offers key benefits for multilingual sites. Server-side rendering and static site generation boost performance and SEO. Dynamic routing and automatic code splitting enhance user experience and scalability.

Ready to take your Next.js web app global? Contact us today to learn how we can help you build an outstanding multilingual site.

Ready to Build Your MVP?

Your product deserves to get in front of customers and investors fast. Let's work to build you a bold MVP in just 4 weeks—without sacrificing quality or flexibility.