versions
- next-translate: ^2.6.2
- next-translate-plugin: ^2.6.2
- next: 14.0.3
- node: 18.17.1
- yarn: 1.22.19
What happened?
I'm using app router on nextjs
In a client component used on a layout, i use useTranslation
(https://github.com/aralroca/next-translate). On server render, all translations is correct. But on client side the translation is not loaded.
The same component work well when used on page.tsx
// src/components/TestClient.tsx
'use client';
import useTranslation from 'next-translate/useTranslation';
export const TestClient = () => {
const { t } = useTranslation('common');
return <div>This is client component, translation value: {t('test')}</div>;
};
// src/components/TestServer.tsx
import useTranslation from "next-translate/useTranslation";
export const TestServer = () => {
const { t } = useTranslation("common");
return <div>This is server component, translation value: {t("test")}</div>;
};
// src/app/layout.tsx
import { TestClient } from "@/components/TestClient";
import { TestServer } from "@/components/TestServer";
export default function RootLayout({ children}: {children: React.ReactNode;}) {
return (
<html lang="en">
<body>
<h2>Inside LAYOUT</h2>
<TestClient />
<TestServer />
{children}
</body>
</html>
);
}
// src/app/page.tsx
import { TestClient } from "@/components/TestClient";
import { TestServer } from "@/components/TestServer";
const Page= () => {
return (
<div>
<h2>Inside PAGE</h2>
<TestServer />
<TestClient />
</div>
);
};
Screenshot of render from server (with javascript browser disabled)
Screenshot of render from client(with javascript browser enabled)
How reproduce?
Github repository for this issue: https://github.com/zeckaissue/next-translate-issue-client-on-layout
Codesandbox for this issue: https://codesandbox.io/p/github/zeckaissue/next-translate-issue-client-on-layout/main
EDIT: This seems related to https://github.com/aralroca/next-translate-plugin/issues/75
Issue is because Next.js handles server side rendering and client side Hyderation.
Make sure that your components and layout are SSR-compatible.
To Prevent client-side code from running during server-side rendering
Use dynamic imports for components that are primarily used on the client side
Make
next-translate
library'swithTranslation
higher-order component for server-side rendering. This ensures that translations are preloaded on the server side before sending the HTML to the client.Dependency