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
Top JSON Translator Tools for 2023

Speed up the localization process for your website or app with the top JSON translator tools. Discover the best options available for developers in 2023!

Author image
DevTranslate
3/9/2023
Easy Vue internationalization - guide to the Vue I18n plugin

How to set up and use the Vue I18n plugin

Author image
DevTranslate
10/26/2023

Translate your
application

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