Can you fetch data in next.config

Viewed 1043

Is there any way to fetch data within the next.config.js file, I am trying to set up i18n but would like for the locales array to be fetched from a CMS rather than statically input by the developer.

1 Answers

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.

Related