📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
added support for ssr i18n
Blue Moused927b2a27f59
diff --git a/app/App.tsx b/app/App.tsxindex e3d377631..d5051bcd7 100644--- a/app/App.tsx+++ b/app/App.tsx@@ -197,7 +197,7 @@ const App = () => {const isMinimalFooter = _some(minimalFooterPages, (page) => _includes(pathname, page))return (- <HocThrowErrorWhenWindowIsUndefined>+ <>{(!accessToken || !loading) && (// eslint-disable-next-line react/jsx-no-useless-fragment<Suspense fallback={<></>}>@@ -222,7 +222,7 @@ const App = () => {</Suspense>)}<div className='hidden' />- </HocThrowErrorWhenWindowIsUndefined>+ </>)}diff --git a/app/entry.client.tsx b/app/entry.client.tsxindex 6d0420d40..af0be7048 100644--- a/app/entry.client.tsx+++ b/app/entry.client.tsx@@ -1,9 +1,3 @@-/**- * By default, Remix will handle hydrating your app on the client for you.- * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨- * For more information, see https://remix.run/file-conventions/entry.client- */-import { RemixBrowser } from '@remix-run/react'import { startTransition, StrictMode } from 'react'import { hydrateRoot } from 'react-dom/client'@@ -11,79 +5,25 @@ import { hydrateRoot } from 'react-dom/client'import i18next from 'i18next'import { I18nextProvider, initReactI18next } from 'react-i18next'import LanguageDetector from 'i18next-browser-languagedetector'-import Backend from 'i18next-http-backend'+import HTTPBackend from 'i18next-http-backend'import { getInitialNamespaces } from 'remix-i18next'-import _isString from 'lodash/isString'-import _includes from 'lodash/includes'-import { whitelist, defaultLanguage } from 'redux/constants'import i18n from './i18n'-import { setItem, getItem } from './utils/localstorage'-async function hydrate() {- const lngDetector = new LanguageDetector()- lngDetector.addDetector({- name: 'customDetector',- lookup() {- if (window.localStorage) {- const lsLang = getItem('language')-- if (_includes(whitelist, lsLang)) {- return lsLang- }-- setItem('language', defaultLanguage)- setItem('i18nextLng', defaultLanguage)- }-- // @ts-ignore- const language = navigator.language || navigator?.userLanguage-- if (_isString(language)) {- const subLanguage = language.substring(0, 2)-- if (_includes(whitelist, subLanguage)) {- return subLanguage- }- }-- return defaultLanguage- },- })-- // @ts-ignoreawait i18next.use(initReactI18next)- .use(lngDetector)- .use(Backend)+ .use(LanguageDetector)+ .use(HTTPBackend).init({...i18n,- backend: {- loadPath: '/locales/{{lng}}.json',- },+ ns: getInitialNamespaces(),+ backend: { loadPath: '/locales/{{lng}}.json' },detection: {- order: ['querystring', 'customDetector', 'htmlTag'],- },- interpolation: {- escapeValue: false,+ order: ['htmlTag'],+ caches: ['cookie'],},- fallbackLng: defaultLanguage,- parseMissingKeyHandler: (key) => {- if (i18next.isInitialized) {- console.warn(`Missing translation for ${key}`)- }- return key- },- whitelist,- ns: getInitialNamespaces(),- defaultNS: 'common',})- i18next.on('languageChanged', (lng) => {- document.documentElement.setAttribute('lang', lng)- setItem('language', lng)- })-startTransition(() => {hydrateRoot(document,@@ -91,7 +31,7 @@ async function hydrate() {<StrictMode><RemixBrowser /></StrictMode>- </I18nextProvider>,+ </I18nextProvider>)})}diff --git a/app/entry.server.tsx b/app/entry.server.tsxindex bd5223a66..8ce3a3d43 100644--- a/app/entry.server.tsx+++ b/app/entry.server.tsx@@ -1,111 +1,66 @@-/**- * By default, Remix will handle generating the HTTP Response for you.- * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨- * For more information, see https://remix.run/file-conventions/entry.server- */-+import type { EntryContext } from '@remix-run/node'import { PassThrough } from 'node:stream'--import type { AppLoadContext, EntryContext } from '@remix-run/node'+import { resolve } from 'node:path'+import { createInstance } from 'i18next'+import { I18nextProvider, initReactI18next } from 'react-i18next'+import FSBackend from 'i18next-fs-backend'import { Response } from '@remix-run/node'import { RemixServer } from '@remix-run/react'import isbot from 'isbot'import { renderToPipeableStream } from 'react-dom/server'+import i18next from './i18next.server'+import i18n, { detectLanguage } from './i18n'+const ABORT_DELAY = 5_000-export default function handleRequest(+export default async function handleRequest(request: Request,responseStatusCode: number,responseHeaders: Headers,remixContext: EntryContext,- loadContext: AppLoadContext,) {- return isbot(request.headers.get('user-agent'))- // eslint-disable-next-line no-use-before-define- ? handleBotRequest(- request,- responseStatusCode,- responseHeaders,- remixContext,- )- // eslint-disable-next-line no-use-before-define- : handleBrowserRequest(- request,- responseStatusCode,- responseHeaders,- remixContext,- )-}+ const instance = createInstance()+ const lng = detectLanguage(request)+ const ns = i18next.getRouteNamespaces(remixContext)-function handleBotRequest(- request: Request,- responseStatusCode: number,- responseHeaders: Headers,- remixContext: EntryContext,-) {- return new Promise((resolve, reject) => {- const { pipe, abort } = renderToPipeableStream(- <RemixServer- context={remixContext}- url={request.url}- abortDelay={ABORT_DELAY}- />,- {- onAllReady() {- const body = new PassThrough()-- responseHeaders.set('Content-Type', 'text/html')-- resolve(- new Response(body, {- headers: responseHeaders,- status: responseStatusCode,- }),- )-- pipe(body)- },- onShellError(error: unknown) {- reject(error)- },- onError(error: unknown) {- responseStatusCode = 500- console.error(error)- },+ await instance+ .use(initReactI18next)+ .use(FSBackend)+ .init({+ ...i18n,+ lng,+ ns,+ backend: {+ loadPath: resolve('./public/locales/{{lng}}.json')},- )+ })- setTimeout(abort, ABORT_DELAY)- })-}+ const callbackName = isbot(request.headers.get('user-agent'))+ ? 'onAllReady'+ : 'onShellReady'-function handleBrowserRequest(- request: Request,- responseStatusCode: number,- responseHeaders: Headers,- remixContext: EntryContext,-) {return new Promise((resolve, reject) => {+ let didError = false+const { pipe, abort } = renderToPipeableStream(- <RemixServer- context={remixContext}- url={request.url}- abortDelay={ABORT_DELAY}- />,+ <I18nextProvider i18n={instance}>+ <RemixServer+ context={remixContext}+ url={request.url}+ abortDelay={ABORT_DELAY}+ />+ </I18nextProvider>,{- onShellReady() {+ [callbackName]: () => {const body = new PassThrough()-responseHeaders.set('Content-Type', 'text/html')-resolve(new Response(body, {headers: responseHeaders,- status: responseStatusCode,+ status: didError ? 500 : responseStatusCode,}),)-pipe(body)},onShellError(error: unknown) {@@ -113,7 +68,7 @@ function handleBrowserRequest(},onError(error: unknown) {console.error(error)- responseStatusCode = 500+ didError = true},},)diff --git a/app/i18n.ts b/app/i18n.tsindex 67c04c647..a1ac86c58 100644--- a/app/i18n.ts+++ b/app/i18n.ts@@ -1,6 +1,44 @@-export default {- supportedLngs: ['en', 'de', 'el', 'es', 'fr', 'hi', 'it', 'pl', 'ru', 'sv', 'uk', 'ru', 'zh'],- fallbackLng: 'en',+import { InitOptions } from 'i18next'+import _includes from 'lodash/includes'++import { defaultLanguage, whitelist } from 'redux/constants'++const genericConfig: InitOptions = {+ supportedLngs: whitelist,+ fallbackLng: defaultLanguage,defaultNS: 'common',react: { useSuspense: false },+ backend: {+ loadPath: '/locales/{{lng}}.json',+ },+ interpolation: {+ escapeValue: false,+ },}++export function detectLanguage(request: Request): string {+ // Stage 1: Getting the language from the query ?lng= parameter+ const url = new URL(request.url)++ if (url.searchParams.has('lng') && _includes(whitelist, url.searchParams.get('lng'))) {+ return url.searchParams.get('lng') as string+ }++ // Stage 2: Getting the language from the cookie+ const cookie = request.headers.get('Cookie')+ const cookieLng = cookie?.match(/(?<=i18next=)[^;]*/)?.[0]++ if (_includes(whitelist, cookieLng)) {+ return cookieLng as string+ }++ // Stage 3: Getting the language from the Accept-Language header or fallback to default+ if (request.headers.has('accept-language') && _includes(whitelist, request.headers.get('accept-language'))) {+ return request.headers.get('accept-language') as string+ }++ // Stage 4: Fallback to default+ return defaultLanguage+}++export default genericConfigdiff --git a/app/i18next.server.ts b/app/i18next.server.tsindex ee66bf671..6562b1974 100644--- a/app/i18next.server.ts+++ b/app/i18next.server.ts@@ -2,23 +2,19 @@ import { RemixI18Next } from 'remix-i18next'import Backend from 'i18next-fs-backend'import { resolve } from 'node:path'import i18n from './i18n'+import { defaultLanguage, whitelist } from 'redux/constants'const i18next = new RemixI18Next({detection: {- supportedLanguages: i18n.supportedLngs,- fallbackLanguage: i18n.fallbackLng,+ supportedLanguages: whitelist,+ fallbackLanguage: defaultLanguage,},- // This is the configuration for i18next used- // when translating messages server-side onlyi18next: {...i18n,backend: {- loadPath: resolve('./public/locales/{{lng}}/{{ns}}.json'),+ loadPath: resolve('./public/locales/{{lng}}.json'),},},- // The backend you want to use to load the translations- // Tip: You could pass `resources` to the `i18next` configuration and avoid- // a backend herebackend: Backend,})diff --git a/app/root.tsx b/app/root.tsxindex cb8d0382c..269eed597 100644--- a/app/root.tsx+++ b/app/root.tsx@@ -1,4 +1,6 @@-import type { LinksFunction } from '@remix-run/node'+import type { LinksFunction, LoaderArgs } from '@remix-run/node'+import { json } from '@remix-run/node'+import { useLoaderData } from '@remix-run/react'import {Links,LiveReload,@@ -10,20 +12,23 @@ import { store } from 'redux/store'import { Provider } from 'react-redux'// @ts-ignoreimport { transitions, positions, Provider as AlertProvider } from '@blaumaus/react-alert'+import BillboardCss from 'billboard.js/dist/billboard.min.css'+import AlertTemplate from 'ui/Alert'import { trackViews } from 'utils/analytics'import { getAccessToken, removeAccessToken } from 'utils/accessToken'import { getRefreshToken } from 'utils/refreshToken'-+import { useChangeLanguage } from 'remix-i18next'+import { useTranslation } from 'react-i18next'import AppWrapper from 'App'+import { detectLanguage } from 'i18n'import mainCss from 'styles/index.css'import tailwindCss from 'styles/tailwind.css'-import BillboardCss from 'billboard.js/dist/billboard.min.css'trackViews()-console.log('%cWelcome, hacker, glad you opened your console, you seem serious about your craft and will go a long way!\nP.S. All the bugs, feature requests are welcome to be sent to [email protected]', 'color: #818cf8;background: #1f2937;font-size: 20px;text-shadow: 2px 2px black')+console.log('%cWelcome, hacker, glad you opened your console, you seem serious about your craft and will go a long way!\nP.S. All the bugs, feature requests are welcome to be sent to [email protected]', 'color: #818cf8background: #1f2937font-size: 20pxtext-shadow: 2px 2px black')const options = {position: positions.BOTTOM_RIGHT,@@ -53,9 +58,24 @@ const removeObsoleteAuthTokens = () => {removeObsoleteAuthTokens()+export async function loader({ request }: LoaderArgs) {+ const locale = detectLanguage(request)++ return json({ locale })+}++export const handle = {+ i18n: 'common',+}+export default function App() {+ const { locale } = useLoaderData<typeof loader>()+ const { i18n } = useTranslation()++ useChangeLanguage(locale)+return (- <html lang='en'>+ <html lang={locale} dir={i18n.dir()}><head><meta charSet='utf-8' /><meta name='viewport' content='width=device-width,initial-scale=1' />