
Google Translate customization#2 under NextJS.
You know, sometimes our first feelings let us down because the world around us is not so simple. I was going to stop withGoogle Translate customization under NextJS. This article reveals an approach to translate any content freely without pain via Google Translate on a NextJS-based project. But a couple of occasions became a game changer.
First, I found one essential improvement regarding language configuration. Second, my colleagueBruno Silva provided me with valuable code improvements. I decided to make a new series by analyzing the factors above. I recommend readingthe previous series if you want to understand my following thoughts.
Let's get started.
The central part of the previous solution ispublic/assets/scripts/lang-config.js contains custom languages settings
window.__GOOGLE_TRANSLATION_CONFIG__={languages:[{title:"English",name:"en"},{title:"Deutsch",name:"de"},{title:"Español",name:"es"},{title:"Français",name:"fr"},],defaultLanguage:"en",};
The solution above is legal, but it doesn't look like a NextJS-pure. I found a more elegant way to define global data through NextJS config. Let's addenv
section tonext.config.js and removepublic/assets/scripts/lang-config.js
/** @type {import('next').NextConfig} */constnextConfig={reactStrictMode:true,env:{GOOGLE_TRANSLATION_CONFIG:JSON.stringify({languages:[{title:"English",name:"en"},{title:"Deutsch",name:"de"},{title:"Español",name:"es"},{title:"Français",name:"fr"},],defaultLanguage:"en",}),},};module.exports=nextConfig;
I also changedpublic/assets/scripts/translation.jsthe following way becausepageLanguage
parameter is not mandatory.
functionTranslateInit(){newgoogle.translate.TranslateElement();}
According to Bruno's proposal, I encapsulated most of the logic into a custom hook,src/hooks/useLanguageSwitcher.ts.
import{useEffect,useState}from"react";import{parseCookies,setCookie}from"nookies";import{NextPageContext}from"next";exportconstCOOKIE_NAME="googtrans";exportinterfaceLanguageDescriptor{name:string;title:string;}exportinterfaceLanguageConfig{languages:LanguageDescriptor[];defaultLanguage:string;}exporttypeUseLanguageSwitcherResult={currentLanguage:string;switchLanguage:(lang:string)=>()=>void;languageConfig:LanguageConfig|undefined;};exporttypeUseLanguageSwitcherOptions={context?:NextPageContext;};exportconstgetLanguageConfig=():LanguageConfig|undefined=>{letcfg:LanguageConfig|undefined;if(process.env.GOOGLE_TRANSLATION_CONFIG){try{cfg=JSON.parse(process.env.GOOGLE_TRANSLATION_CONFIG??"{}");}catch(e){}}returncfg;};exportconstuseLanguageSwitcher=({context,}:UseLanguageSwitcherOptions={}):UseLanguageSwitcherResult=>{const[currentLanguage,setCurrentLanguage]=useState<string>("");useEffect(()=>{constcfg=getLanguageConfig();constcookies=parseCookies(context);constexistingLanguageCookieValue=cookies[COOKIE_NAME];letlanguageValue="";if(existingLanguageCookieValue){constsp=existingLanguageCookieValue.split("/");if(sp.length>2){languageValue=sp[2];}}if(cfg&&!languageValue){languageValue=cfg.defaultLanguage;}setCurrentLanguage(languageValue);},[]);constswitchLanguage=(lang:string)=>()=>{setCookie(context,COOKIE_NAME,"/auto/"+lang);window.location.reload();};return{currentLanguage,switchLanguage,languageConfig:getLanguageConfig(),};};exportdefaultuseLanguageSwitcher;
Important note.process.env.GOOGLE_TRANSLATION_CONFIG
allows us to get GOOGLE_TRANSLATION_CONFIG variable from the above mentioned NextJS config.
A couple of final stitches.
src/components/lang-switcher.tsx
import{NextPageContext}from"next";importuseLanguageSwitcher,{LanguageDescriptor,}from"@/hooks/useLanguageSwitcher";importReactfrom"react";exporttypeLanguageSwitcherProps={context?:NextPageContext;};exportconstLanguageSwitcher=({context}:LanguageSwitcherProps={})=>{const{currentLanguage,switchLanguage,languageConfig}=useLanguageSwitcher({context});if(!languageConfig){returnnull;}return(<divclassName="text-center notranslate">{languageConfig.languages.map((ld:LanguageDescriptor,i:number)=>(<React.Fragmentkey={`l_s_${ld}`}>{currentLanguage===ld.name||(currentLanguage==="auto"&&languageConfig.defaultLanguage===ld.name)?(<spanclassName="mx-3 text-orange-300">{ld.title}</span>):(<aonClick={switchLanguage(ld.name)}className="mx-3 text-blue-300 cursor-pointer hover:underline">{ld.title}</a>)}</React.Fragment>))}</div>);};exportdefaultLanguageSwitcher;
useLanguageSwitcher
looks elegant :)
src/pages/_document.tsx
import{Html,Head,Main,NextScript}from"next/document";importScriptfrom"next/script";exportdefaultfunctionDocument(){return(<Html><Head><Scriptsrc="/assets/scripts/translation.js"strategy="beforeInteractive"/>{process.env.GOOGLE_TRANSLATION_CONFIG&&(<Scriptsrc="//translate.google.com/translate_a/element.js?cb=TranslateInit"strategy="afterInteractive"/>)}</Head><body><Main/><NextScript/></body></Html>);}
We don't even physically include the translation engine if the config is missing.
You can find the final solutionhere.
May the Google Translate, NextJS, and Force be with you!
Top comments(2)

- LocationKharkiv, Ukraine
- Educationhttps://www.kpi.kharkov.ua/eng/
- Workhttps://valor-software.com/
- Joined
@kawtharklayshe This is a question of RTL support. Please, look atgithub.com/buchslava/nextjs-gtrans...
The solution above is not 100% perfect, but it illustrates how it works.
For further actions, you may consider blocking this person and/orreporting abuse