From 78804df64b28f718c3c8ec7159a8bb20088eb2b4 Mon Sep 17 00:00:00 2001 From: Isaac Hinman Date: Wed, 24 Feb 2021 10:22:52 +0000 Subject: [PATCH] fix: Add server side loading of fallbackLng --- src/config/createConfig.test.ts | 28 ++++++++++++++++++++++++++++ src/config/createConfig.ts | 4 ++++ src/serverSideTranslations.ts | 12 +++++++++--- 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/src/config/createConfig.test.ts b/src/config/createConfig.test.ts index bf260c13..1026b921 100644 --- a/src/config/createConfig.test.ts +++ b/src/config/createConfig.test.ts @@ -69,6 +69,34 @@ describe('createConfig', () => { } as UserConfig) expect((config.detection as any).hello).toEqual('world') }) + + describe('fallbackLng', () => { + it('automatically sets if it user does not provide', () => { + const config = createConfig({ + lng: 'en', + } as UserConfig) + + expect(config.fallbackLng).toBe('en') + }) + + it('does not overwrite user provided value', () => { + const config = createConfig({ + fallbackLng: 'hello-world', + lng: 'en', + } as UserConfig) + + expect(config.fallbackLng).toBe('hello-world') + }) + + it('does not overwrite user provided boolean', () => { + const config = createConfig({ + fallbackLng: false, + lng: 'en', + } as UserConfig) + + expect(config.fallbackLng).toBe(false) + }) + }) }) describe('when filesystem is missing defaultNS', () => { diff --git a/src/config/createConfig.ts b/src/config/createConfig.ts index fc90bfcf..5286d5f3 100644 --- a/src/config/createConfig.ts +++ b/src/config/createConfig.ts @@ -37,6 +37,10 @@ export const createConfig = (userConfig: UserConfig): InternalConfig => { return combinedConfig as InternalConfig } + if (typeof combinedConfig.fallbackLng === 'undefined') { + combinedConfig.fallbackLng = combinedConfig.defaultLocale + } + if (!process.browser) { combinedConfig.preload = locales diff --git a/src/serverSideTranslations.ts b/src/serverSideTranslations.ts index e5e02cc0..1ae28473 100644 --- a/src/serverSideTranslations.ts +++ b/src/serverSideTranslations.ts @@ -40,10 +40,16 @@ export const serverSideTranslations = async ( [initialLocale]: {}, } + if (typeof config.fallbackLng === 'string') { + initialI18nStore[config.fallbackLng] = {} + } + namespacesRequired.forEach((ns) => { - initialI18nStore[initialLocale][ns] = ( - (i18n.services.resourceStore.data[initialLocale] || {})[ns] || {} - ) + for (const locale in initialI18nStore) { + initialI18nStore[locale][ns] = ( + (i18n.services.resourceStore.data[locale] || {})[ns] || {} + ) + } }) return {