Search code examples
next.jsinternationalizationi18nextgraphcms

How can I load an i18n json from a CMS with i18next?


I am using https://github.com/i18next/next-i18next and rather than hardcoding the files, I want to use HygraphCMS (formerly GraphCMS) to provide those strings. What's the best way to approach this?

If I wait for an async request, it'll slow things down. Thanks in advance!


Solution

  • The best solution here would depend on how you have the rest of the Next.js project set up and how much you want to avoid an async request. I've described two approaches I would consider below. Both examples assume you're using Next.js and hosting on Vercel, but it should be possible and similar through other platforms.

    1. Build script to store locally (without async request)

    Start by writing a script to fetch all the translations and store them locally in the project (just as Aldabil21 said).

    After that, you can create a deploy webhook and call it from your CMS whenever a change is made; this will ensure that the translations are always kept up-to-date. An issue with this could be that the build runs too often, so you may want to add some conditions here to prevent that, such as only calling the webhook from the CMS when the translations content changes.

    2. Using incremental static regeneration (with async request)

    Of course, if you're using incremental static regeneration, you might reconsider fetching the translations using getStaticProps as the request is not made for each visitor.

    The result of the request to the CMS's translation collection would be cached on Vercel's Edge network and then shared amongst each visitor, so only the first request after the cache has expired will trigger the full request. The maximum age for the caching of static files is 31 days, so this delay when requesting fresh data could be infrequent enough to be acceptable. Note that you have to enable this manually by setting the revalidate prop in the return object of getStaticProps.

    You could even mitigate this request further (depending on your project setup) by querying only for the language that is currently used, and querying a new language client-side only when it is requested by the visitor (or possibly once the page is idle or the language switcher is opened). If you have many languages, this reduction will reduce the download time substantially.

    If you do go the getStaticProps route and are using Next.js >12.2.0 then you could also create a CMS webhook to call the on-demand revalidation endpoint whenever a page is updated, which will cause the fresh translations to be stored in cache before a user gets a chance to request it, removing the delay for all users. Or you could use the webhook in the same way as mentioned in 1 and trigger a new build (with the new translations) every time the translation collection is updated.