Reputation: 5159
In Next.js, when using next-translate
i18n plugin with dynamic routes, it does not work with non-default locale.
I have 2 locales. Arabic "ar" and English "en". The default locale is "ar".
When I access this URL for example: domain.com/post/1
it appears as expected and shows the Arabic content.
On the other hand, when I try to access the English version of the same post through this URL: domain.com/en/post/1
it doesn't appear and gives 404 (Not Found) error.
How to fix this issue?
Upvotes: 0
Views: 1061
Reputation: 5159
Here is a full example representing how to generate dynamic paths for both default and non-default locales when using text-translate
i18n internationalization plugin with dynamic routes in Next.js:
// File: lib/local-data.js
import fs from "fs";
import path from "path";
export async function getLocalJsonData(localJsonFilePath) {
// Get the path of the json file
const filePath = path.join(process.cwd(), localJsonFilePath);
// Read the json file
const fileContent = fs.readFileSync(filePath, "utf8");
// Parse data as json
const jsonData = JSON.parse(fileContent);
return jsonData;
}
.
// File: pages/post/[postId].js
import { getLocalJsonData } from "@/lib/local-data";
import useTranslation from "next-translate/useTranslation";
export async function getStaticPaths({ locales }) {
// Reading local json data.
// Supposing you store your data in a json file within the project
const posts = await getLocalJsonData("/data/json/posts.json");
// Generate dynamic paths for default and non-default locales.
const paths = posts.flatMap((post) =>
locales.map((locale) => ({
params: { postId: String(post.id) },
locale,
}))
);
// { fallback: false } means other routes should 404.
return { paths, fallback: false };
}
export async function getStaticProps({ params }) {
// Reading local json data.
const posts = await getLocalJsonData("/data/json/posts.json");
// Return the value of the first element that passes the given test.
const postObject = posts.find((post) => {
return String(post.id) === String(params.postId);
});
return { props: { postObject } };
}
export default function Post({ postObject }) {
({ t: translate, lang: currentLocale } = useTranslation());
return (
<>
<h1>
{currentLocale === "ar"
? postObject.ar?.title
: postObject.en?.title}
</h1>
<div>
{currentLocale === "ar"
? postObject.ar?.content
: postObject.en?.content}
</div>
</>
);
}
Upvotes: 0