問題描述
你能在 next.config 中獲取數據嗎 (Can you fetch data in next.config)
有什麼方法可以在 next.config.js 文件中獲取數據,我正在嘗試設置 i18n,但希望從 CMS 獲取語言環境數組,而不是由開發人員靜態輸入。
參考解法
方法 1:
From Next.js docs: (https://nextjs.org/docs/api‑reference/next.config.js/introduction)
next.config.js is a regular Node.js module, not a JSON file. It gets used by the Next.js server and build phases, and it's not included in the browser build.
It means that you can do something like this:
module.exports = {
async headers() {
const response = await fetch("https://example.com/langs");
const dt = await response.json();
return [
{
source: "/api/dashboard",
headers: [{ key: "Lang", value: dt.map((d) => d.lng).join(",") }],
},
];
},
};
Obviously the above code can be done inside the endpoint handler but I just wanted to give an example to prove it's working.
(by Aiden Barrett、Sirwan Afifi)