Back to Blog
Blog post illustration

Auto reload locales in Nextjs without restarting the server

Constantly restarting to see the changes you've made to your json files can get tiresome really fast - fortunately theres a neat trick available with next-i18next to avoid that.

If you just want to see the code, here is what we use:

import nextI18nextConfig from '@/../next-i18next.config';
import { MyResources } from '@/types/next-i18next';
import { i18n } from 'next-i18next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';

interface ContextModel {
	params: { locale: string };
}

const getI18nPaths = () =>
	nextI18nextConfig.i18n.locales.map((lng) => ({
		params: {
			locale: lng,
		},
	}));

export const getStaticPaths = () => ({
	fallback: false,
	paths: getI18nPaths(),
});

async function getI18nProps(ctx: ContextModel, ns: Array<keyof MyResources> = ['common']) {
	const locale = ctx?.params?.locale || 'en';
	if (process.env.NODE_ENV === 'development') {
		await i18n?.reloadResources();
	}
	const props = {
		...(await serverSideTranslations(locale, ns)),
	};

	return props;
}

export function makeStaticProps(ns: Array<keyof MyResources>) {
	return async function getStaticProps(ctx: ContextModel) {
		return {
			props: await getI18nProps(ctx, ns),
		};
	};
}

The gist of it is the part with reloadResources here:

async function getI18nProps(ctx: ContextModel, ns: Array<keyof MyResources> = ['common']) {
    const locale = ctx?.params?.locale || 'en';
    if (process.env.NODE_ENV === 'development') {
        await i18n?.reloadResources();
    }
    const props = {
        ...(await serverSideTranslations(locale, ns)),
    };

Simple as that, with this little addition we can say goodbye to restarting the server every time to see the translations (which gets tiresome really fast)

Additionally if you want to you can also pass an array of languages or namespaces into the brackets after reloadResources if you only want to reload content in some particular language or some specific space instead of reloading everything. If you ever had to restart the server multiple times to see the translations I bet I don't have to sell you on this.

You may also like
Reaching a global audience through localization

How to gain users by localizing your app and who/what to rely on for translation.

Author image
DevTranslate
10/4/2022
A Quick Guide to App Localization - DevTranslate

Application localization is the process of adapting your application to the culture & language of each target market in which you would like to succeed.

Author image
DevTranslate
9/18/2022
9 XML Translator Tools for 2023 with Pros and Cons

Looking for the best XML translator tool? Check out our list of 9 translators for 2023 with pros and cons and pick the right one for you.

Author image
DevTranslate
2/28/2023

Translate your
application

Don't waste your time! Use our hassle-free online arb, strings xml & json translator.
Try it for free