Next.js Discord

Discord Forum

Avoid any code to be run at build time (because env vars are provided at runtime)

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
Even if I marked all my routes with export const dynamic = "force-dynamic";, a file imported in a route will be executed at build time.

// file a.ts
const validateEnvVars = () => {
  // do something with env vars
  if (someError) {
    throw new Error("An error that will be thrown at build time because env vars are not available at this point");
  }
}

validateEnvVars()
// file page.tsx
export const dynamic = "force-dynamic";
import "./a.ts";
...


Use case: I want to validate my env vars at runtime with zod. Since these env vars are not available at this point, the validation throws an error.

I do not want to validate environment variables on each request, only at startup (that’s why the validation lives at the top level). Before that I used instrumentation.ts but I do not think this is the proper solution.

0 Replies