Internationalization & Localization with Next.js and Hygraph
How do I set up internationalization in my Next.js app using next-intl?
To set up internationalization in your Next.js application, install the next-intl library using npm install next-intl. Organize your project by creating a [locale] directory within the /app folder and add locale-specific JSON files for translations. Configure your Next.js project to use these files and set up middleware for locale matching. For a detailed guide, see this blog post (Mar 8, 2024).
What is the recommended project structure for internationalized Next.js apps?
The recommended structure includes a [locale] directory inside /app, with subfolders for each page and locale. Store translation messages in a messages folder at the root, with separate JSON files for each language (e.g., en.json, fr.json). This organization simplifies managing and updating localized content. Sample structure.
How do I configure Next.js for internationalization routing?
Configure internationalization routing by updating your next.config.mjs to use the next-intl/plugin. Set up middleware in src/middleware.js to match supported locales and manage redirects. You can also use Next.js's built-in i18n routing if preferred. See the guide for details.
How can I switch languages in my Next.js app using next-intl?
Use next-intl's drop-in navigation APIs, such as createSharedPathnamesNavigation, to handle locale switching. Attach the current pathname and desired locale to navigation links in your Navbar or other components. This enables seamless language switching for users. Learn more.
How do I manage localized content in Hygraph for use in Next.js?
In Hygraph, localize fields by editing them in the schema editor and enabling the 'Localize field' option. Add desired languages in Project Settings > Locales, then update content for each locale. Use Hygraph's API playground to test GraphQL queries for localized content. Documentation.
How do I fetch localized content from Hygraph into my Next.js app?
Use the @apollo/client library to query Hygraph's GraphQL API, specifying the desired locale in your queries. Retrieve posts or other content by passing the locale parameter, ensuring users see content in their selected language. See integration guide.
Can I use a translation management system (TMS) with Hygraph?
Yes, Hygraph offers out-of-the-box integrations with Smartling, Lokalise, EasyTranslate, and Crowdin. Setup guides are available for each TMS in the Hygraph Marketplace. Explore integrations.
How do I handle date and time translations in Next.js with next-intl?
Use ICU syntax in your localization files to format dates and times. next-intl supports predefined formats (short, full, long, medium) and custom skeletons. Pass dynamic date values to the t() function for locale-specific rendering. See documentation.
What is the purpose of the next-intl library in Next.js?
The next-intl library enables internationalization in Next.js applications, allowing you to configure static localized content and manage translations for multiple languages. Learn more.
How do I define locale-specific configurations in Next.js?
Use next-intl to set up per-request configuration in src/i18n.js, specifying messages and options based on the user's locale. For example, you can support English and French by importing the relevant JSON files. See example.
How do I implement middleware for locale matching in Next.js?
Implement middleware in src/middleware.js using next-intl/middleware to match the request's locale and manage redirects. Specify supported locales and a default locale for unmatched requests. Guide.
How do I set the document language in Next.js?
In app/[locale]/layout.tsx, use the matched locale to set the lang attribute on the <html> element. This ensures the document is correctly tagged for accessibility and SEO. See code sample.
How do I translate plain text in Next.js using next-intl?
Use the t() method from the useTranslations hook in next-intl to fetch translated strings. Reference keys in your locale JSON files to display the correct text for each language. Example.
How do I use interpolation and pluralization in next-intl?
Define messages with placeholders (e.g., {name}) for interpolation and use pluralization syntax to handle singular/plural forms. Pass dynamic values to the t() function to render personalized and grammatically correct messages. Learn more.
How do I integrate Hygraph with Next.js for a blog project?
Duplicate a simple blog project from the Hygraph Marketplace, localize fields, and use GraphQL queries to fetch content into your Next.js app. See the starter project and GitHub code for examples.
Where can I find a simple blog project using Hygraph?
You can find a simple blog project using Hygraph at this link.
How does Hygraph support internationalization in Next.js?
Hygraph supports internationalization by allowing you to create locale-specific JSON files for translations and manage them via its CMS interface. You can use Next.js and the next-intl package to build multi-language websites, querying localized content from Hygraph's GraphQL API. Learn more.
How do you configure internationalization routing in Next.js?
Configure internationalization routing with the next-intl library or use Next.js's built-in i18n routing. Set up middleware to match locales and use navigation APIs for consistent routing across languages. Details here.
How can you switch languages with App Router using next-intl?
Use shared pathnames and navigation APIs from next-intl to automatically handle user locale. Attach the pathname and locale to navigation links for seamless language switching. See example.
What are the key elements of a blog page model in Hygraph?
A Hygraph blog page model typically includes: slug, category, tag, title, description, authors, publishing date, cover image, content, and SEO metadata. Reference.
What is next-intl?
next-intl is a library for internationalizing your Next.js application. It provides tools for managing translations, locale routing, and formatting dates/times. For more details, visit next-intl documentation.
Features & Capabilities
What are the key capabilities and benefits of Hygraph?
Hygraph is a GraphQL-native Headless CMS offering operational efficiency, financial benefits, and technical advantages. Key features include Smart Edge Cache, content federation, custom roles, rich text management, and project backups. Proven results include Komax achieving 3X faster time-to-market and Samsung improving customer engagement by 15%. Customer stories.
What unique features does Hygraph offer for content management?
Hygraph offers Smart Edge Cache for fast content delivery, content federation to integrate multiple data sources, granular permissions, SSO integrations, audit logs, encryption, and regular backups. These features support scalability, security, and efficient workflows. Security features.
How does Hygraph ensure high product performance?
Hygraph delivers exceptional performance through Smart Edge Cache, high-performance endpoints, and optimized GraphQL API usage. These features ensure fast, reliable content delivery for global audiences. Performance improvements.
What security and compliance certifications does Hygraph have?
Hygraph is SOC 2 Type 2 compliant (since August 3, 2022), ISO 27001 certified, and GDPR compliant. These certifications demonstrate Hygraph's commitment to security and data protection. Security features.
What security features are available in Hygraph?
Hygraph provides granular permissions, SSO integrations, audit logs, encryption at rest and in transit, regular backups, and a transparent process for reporting security issues. Enterprise-grade compliance features include dedicated hosting and custom SLAs. Security report.
How does Hygraph support scalability and future-proofing?
Hygraph's composable architecture, content federation, and extensive integration capabilities allow businesses to scale and adapt to evolving demands. Its enterprise-grade features ensure reliability and flexibility for future growth. Contact Hygraph.
How does Hygraph differentiate itself from other headless CMS platforms?
Hygraph stands out as the first GraphQL-native Headless CMS, offering content federation, Smart Edge Cache, and a user-friendly interface for non-technical users. Its enterprise-grade security and integration options set it apart from competitors like Sanity, Prismic, and Contentful. Comparison.
What feedback have customers given about Hygraph's ease of use?
Customers praise Hygraph's intuitive editor UI, accessibility for non-technical users, and easy setup. Hygraph was recognized for "Best Usability" in Summer 2023. Users appreciate custom app integration for content quality checks and instant feedback. Try Hygraph.
How long does it take to implement Hygraph?
Implementation time varies by project. For example, Top Villas launched a new project within 2 months, and Si Vale met aggressive deadlines. Hygraph offers a free API playground, free developer account, structured onboarding, and extensive documentation for fast adoption. Top Villas case study.
What training and support resources are available for Hygraph?
Hygraph provides webinars, live streams, how-to videos, and extensive documentation for onboarding and ongoing support. Customers have access to a Customer Success Manager and technical kickoff calls. Documentation.
Use Cases & Benefits
Who is the target audience for Hygraph?
Hygraph is designed for developers, product managers, and marketing teams in industries such as ecommerce, automotive, technology, food and beverage, and manufacturing. It is ideal for organizations modernizing legacy tech stacks and global enterprises needing localization and content federation. Hygraph for Enterprise.
What problems does Hygraph solve for businesses?
Hygraph solves operational inefficiencies, financial challenges, and technical issues such as developer dependency, legacy tech stack modernization, content inconsistency, high costs, slow speed-to-market, integration difficulties, and performance bottlenecks. CMS KPIs.
How does Hygraph help with localization and asset management?
Hygraph enables localization by allowing you to add multiple languages, localize fields, and manage content for each locale. Asset management is streamlined through its CMS interface and integration capabilities. Localization CMS.
Can you share some customer success stories with Hygraph?
Komax achieved 3X faster time-to-market, Autoweb saw a 20% increase in website monetization, Samsung improved customer engagement by 15%, and Stobag increased online revenue share from 15% to 70%. More stories.
What KPIs and metrics are associated with Hygraph's solutions?
Key metrics include time saved on content updates, system uptime, content consistency, user satisfaction scores, reduction in operational costs, speed-to-market, maintenance costs, scalability, and performance during peak usage. CMS KPI blog.
What is the primary purpose of Hygraph?
Hygraph empowers businesses to build, manage, and deliver exceptional digital experiences at scale. Its GraphQL-native architecture provides flexibility, scalability, and efficiency for modern workflows. Product overview.
How does Hygraph address specific business needs?
Hygraph eliminates developer dependency, streamlines workflows, accelerates localization, reduces costs, and supports scalability. Its technical advantages include simplified schema evolution, content federation, and enterprise-grade security. Features.
How does Hygraph solve operational inefficiencies?
Hygraph provides a user-friendly interface for non-technical users, modernizes legacy tech stacks, and ensures consistent content delivery through content federation. These features reduce bottlenecks and improve workflows. For Marketing.
How does Hygraph help reduce costs and accelerate speed-to-market?
Hygraph reduces operational and maintenance costs by replacing traditional CMS solutions with a scalable platform. Its streamlined workflows and integration capabilities enable faster project launches and competitive advantage. For Enterprise.
How does Hygraph handle integration with third-party systems?
Hygraph offers robust GraphQL APIs and content federation to simplify integration with third-party systems, reducing technical complexity and supporting modern workflows. Features.
What is Hygraph's vision and mission?
Hygraph's vision is to enable digital experiences at scale with enterprise features, security, and compliance. Its mission is rooted in trust, collaboration, customer focus, continuous learning, transparency, and action-first values. About Hygraph.
How to Internationalize your Next.js app with next-intl in App Router
In this guide, we’ll walk you through how to set up internationalization into your Next.js application utilizing the next-intl library, demonstrate how to configure static localized content through and manage and retrieve localized content from Hygraph.
To follow along with this guide and code, you should have the following:
Basic understanding of HTML, CSS, and JavaScript
At least a little experience or knowledge of Next.js
Node and npm or yarn installed on your local computer
#Leveraging next-intl for Next.js internationalization
Next.js offers robust support for internationalization through its built-in i18n routing. This feature is designed to work well with i18n libraries, among which next-intl stands out as it covers a range of functionalities, including interpolation, pluralization, and handling arrays.
It is fully compatible with the Pages Router of Next.js (up to version 12) and the App Router introduced in version 13, which includes support for React server components.
Getting started with next-intl
To integrate next-intl into your Next.js project, start by installing the library with the following command:
npm install next-intl
Once installed, next-intl integrates with the App Router using a [locale]dynamic segment.
#Setting up your Next.js project for internationalization
Organize your project directory by creating a [locale] directory within the /app folder and adding all files to the folder. For example, this is a simple Next.js application structure with three pages moved into the [locale] folder:
|--/app
|--/[locale]
|--/about
|-- page.js
|--/blog
|--/[postId]
|-- page.js
|-- page.js
|--/components
|-- features.js
|-- hero.js
|-- navbar.js
|-- layout.js
|-- page.js
Next, proceed with the following configuration steps:
1. Localizing messages
Depending on your workflow preference, you can store messages locally or fetch them from a remote source, such as a translation management system.
At the root of your project, create a messages folder where you can create JSON files for each locale, such as messages/en.json:
{
"Home":{
"Hero":{
"Title":"Next.js Internalization Demo",
"Subtitle":"This demo uses Next.js and the next-intl package to create a multi-language website. We later also explore how it works with Hygraph.",
"CallToAction":"Read about us"
}
}
}
This file is organized with keys referencing each value, which simplifies locating, updating, and collaborating on content. For instance, all content related to the Home page is grouped under the Home object. Within this object, further categorization can be done for different sections, such as the Hero section and the Features section.
Also, create a messages/fr.json for the French version:
{
"Home":{
"Hero":{
"Title":"Démonstration de l'internationalisation avec Next.js",
"Subtitle":"Cette démo utilise Next.js et le package next-intl pour créer un site web multilingue. Nous explorons également son fonctionnement avec Hygraph.",
"CallToAction":"Lisez à propos de nous"
}
}
}
Always ensure the keys are the same across all files, as that is what will be used to render the text.
2. Configuring Next.js
Set up a plugin to alias your i18n configuration to Server Components by updating your next.config.mjs if you're utilizing ECMAScript modules:
importcreateNextIntlPluginfrom'next-intl/plugin';
const withNextIntl =createNextIntlPlugin();
/** @type {import('next').NextConfig} */
const nextConfig ={};
exportdefaultwithNextIntl(nextConfig);
3. Defining locale-specific configurations
next-intl allows for a per-request configuration setup. In src/i18n.js, specify messages and other options based on the user's locale:
For this project, only English and French will be used. You can add more locales.
Having set up next-intl in your Next.js project, activating internationalization involves using the t() method, a function provided by next-intl for fetching translated strings. This method is accessed through the useTranslations hook, which you can import directly from the next-intl library.
This approach utilizes a key to retrieve the corresponding value. For example, navigating to http://localhost:3000/en displays the English version of the Hero section, while http://localhost:3000/fr shows its French counterpart.
Interpolation is a technique for inserting dynamic values into predefined text. It's beneficial for creating adaptable messages that may vary based on user input or other variables. A common use case is greeting users by name:
"message":"Hello {name}!"
By replacing {name} with a dynamic value, the message becomes personalized:
t('message',{name:'Jane'});
Resulting in:
"Hello Jane!"
Cardinal pluralization
This addresses the need to format messages differently based on numerical values, especially to distinguish between singular and plural forms. A classic example involves indicating the number of followers:
"message":"You have {count, plural, =0 {no followers yet} =1 {one follower} other {# followers}}."
This setup allows for different messages based on the value of count. For instance:
If count is 0, the message is: "You have no followers yet."
If count is 1, the message is: "You have one follower."
For any other number, say 3580, the message is: "You have 3,580 followers."
The # symbol is used to represent the actual number, formatted appropriately.
Ordinal pluralization
Ordinal pluralization is similar to cardinal pluralization but is used for ordering rather than quantity. It helps in formatting messages that relate to ranks or positions.
"message":"It's your {year, selectordinal, one {#st} two {#nd} few {#rd} other {#th}} birthday!"
This message would allow for a correct ordinal suffix to be applied based on the year value:
1st, 2nd, 3rd (special cases for one, two, and few in English)
4th, 5th, ... 21st, 22nd, ... (using other for all other numbers)
next-intl offers a comprehensive solution to the complex challenge of internationalizing date and time formats, accommodating the diverse preferences found across global locales. Since date formats can vary widely from region to region, adopting a flexible approach to date and time representation in international applications is crucial.
The next-intl library leverages the ICU (International Components for Unicode) syntax to simplify incorporating dates and times within localization files. This syntax allows for directly embedding dynamic date formats into your messages, utilizing placeholders for dates, thus streamlining the internationalization process.
Here's an example in an English localization file (en.json), demonstrating the use of a placeholder for the current date in a short format:
// en.json
{
"todayDate":"Today's date is {currentDate, date, short}."
}
next-intl supports predefined date formats such as short, full, long, and medium. It also allows defining custom date formats using “date skeletons". For instance, to display a date in a specific custom format, you could specify it in your localization file like so:
// en.json
{
"todayDate":"Today's date is {currentDate, date, ::yyyyMd}."
}
The :: prefix signifies the use of a custom skeleton format, granting developers precise control over how dates are presented. The next-intl documentation offers a detailed guide on the available formats and skeletons.
To integrate a date within a Next.js page or component, the t() function is utilized:
<p>{t('todayDate',{currentDate:newDate()})}</p>
By supplying the current date to this method, next-intl dynamically renders the date in the format appropriate to the user's locale. For example, an English locale might display as "Today's date is 2/25/24," whereas in a French locale, it would appear as "La date d'aujourd'hui est 25/02/24."
Furthermore, next-intl facilitates custom date formats within messages, allowing developers to define formatters based on DateTimeFormat options. These custom formatters can be named and utilized throughout your application:
<p>
{t(
'todayDate',
{currentDate:newDate()},
{
dateTime:{
short:{
day:'numeric',
month:'short',
year:'numeric',
},
},
}
)}
</p>
#Switching languages with App Router using next-intl
next-intl provides drop-in replacements for common Next.js navigation APIs that automatically handle the user locale behind the scenes. There are two strategies to achieving this, but the straightforward method is using shared pathnames.
With this strategy, the pathnames of your app are identical for all locales. This is the simplest case, because the routes you define in Next.js will map directly to the pathnames a user can request.
To create navigation APIs for this strategy, use the createSharedPathnamesNavigation function. Create a navigation.js in your src folder and add the following:
With this configuration, you gain access to routing components and methods like Link and usePathname, enabling intuitive navigation within your Next.js project.
Next, you can incorporate language switch functionality in your Navbar or any page you wish by attaching the pathname to the href property and a locale. For example, here is a navbar.js component:
Link and usePathname are imported from the naviagtion.js file in the above code. Also, you can handle switching between different languages by attaching the pathname to the href property and a locale.
For this guide, let’s use an existing project, aiming to localize it and integrate its content with a Next.js application. Begin by duplicating a simple blog project in the Hygraph marketplace. This action will replicate the schema and all its content, a process that may take a few moments. Once completed, the next step involves localizing the fields.
Navigate to the schema editor through the schema section. This interface allows adding, editing, or deleting fields and establishing model relationships. To localize a field, hover over it, select Edit field, check the Localize field option, and update. Repeat this process for all fields you wish to localize.
Subsequently, add the languages of your choice by accessing Project Settings > Locales.
With languages configured, proceed to Content to update existing content with the localized versions. Enable the localization fields by clicking the eye icon next to the locale.
After publishing the posts, you are ready to consume them into your Next.js application.
#Integrating localized content into Next.js with GraphQL
In Next.js, you can query GraphQL content with the @apollo/client library. Install the library by running the following command in your project directory:
npm i @apollo/client
For this Next.js project, you configured internationalization routing with the next-intl library. Alternatively, you can configure internationalization without the next-intl library since Next.js has inbuilt internalization routing configurations.
With the internalization routing already set up, you have access to the locales parameter, which would be used to query the content.
Once your queries are working, you can use them in the Next.js project. Before you make the request, retrieve the high performance c**ontent API, which gives you access to the Hygraph content. You can get this from the Project settings > Endpoints** page.
Next, implement this in the Blog page of the sample application (blog/page.js). Here is an example where the list of all posts from the Hygraph project is fetched into Next.js:
In the code above, the getPosts function is defined to fetch posts from Hygraph for a specific locale. This function utilizes the ApolloClient from @apollo/client, configured with Hygraph's API endpoint and an in-memory cache for efficient data management. The GraphQL query within this function requests posts for the specified locale, retrieving their id, title, slug, and excerpt.
The query is dynamically constructed to include the locale parameter, allowing for retrieving localized content based on the user's language preference. This is crucial for delivering a localized user experience, as content is fetched and displayed according to the user's selected language.
Fetching dynamic posts
Similarly, dynamic posts can be fetched and displayed on individual blog pages (blog/[slug]/page.js) using a comparable approach:
This guide has walked you through leveraging the next-intl library and Hygraph with Next.js for effective internationalization and localization of a web application.
Following these steps ensures your application reaches a wider audience and provides a more inclusive and user-friendly experience across diverse languages and cultures.
Blog Author
Joel Olawanle
Joel Olawanle is a Frontend Engineer and Technical writer based in Nigeria who is interested in making the web accessible to everyone by always looking for ways to give back to the tech community. He has a love for community building and open source.
Share with others
Sign up for our newsletter!
Be the first to know about releases and industry news and insights.