My ultimate goals to achieve translated metadata in Next.js server-side components.
Here’s a valid code of mine in a app/[lang]/admin/page.tsx
:
import { Metadata } from "next";
interface IProps {
params: {
lang: string;
};
}
import { serverLang } from "@/app/[lang]/dictionaries.js";
export async function generateMetadata({
params: { lang },
}: IProps): Promise<Metadata> {
const t = await serverLang(lang);
return {
title: t("Dashboard"),
};
}
export default async function Dashboard({ params: { lang } }: IProps) {
const t = await serverLang(lang);
return (
<div>
<p>{t("Dashboard")}</p>
</div>
);
};
I want to simplify the metadata
declaration in every component simply like below:
export const metadata = {
title: t("Next.js"), // 🔴 t() is not available
description: t("Generated by Next.js"),
};
export default async function Dashboard({ params: { lang } }: IProps) {
const t = await serverLang(lang);
// ...rest of the code here
};
or something as simple as:
import { setMetadata } from "@/utils/metadata";
setMetadata("Next.js", "Generated by Next.js"); // translation will be done inside the function
// Dashboard() component code here
What I tried so far
I’ve made a custom file with all the relavant code like:
import { Metadata } from "next";
interface IProps {
params: {
lang: string;
};
}
import { serverLang } from "@/app/[lang]/dictionaries.js";
export async function generateMetadata({
params: { lang },
}: IProps): Promise<Metadata> {
const t = await serverLang(lang);
return {
title: t("Dashboard"),
};
}
export function setMetadata = (title, description) => {
// 👉 I got stuck here
}