labnotes

Load enviroments the nextjs way

for scripts

tags
nextjs
jaascript
environment

Contents

I have a couple of scripts that I want to run outside of the NextJS server process, and the scripts live in the same directory. This is how you load up the environment.

For example, test/image.mjs:

1
2
3
4
5
6
7
8
9
  import pkg from "@next/env";
  const { loadEnvConfig } = pkg;
  const projectDir = process.cwd(); // Your project's root directory
  const dev = process.env.NODE_ENV !== "production"; // Check if in development mode

  // Load the environment variables
  loadEnvConfig(projectDir, dev);

  console.log("Loaded environment variables:", process.env.OPENAI_API_KEY);

And then

1
  node test/image.mjs

Previously

fragments

The Focus AI

I’m back

tags

Next

fragments

Unnecessary Knowledge

keep it lean

tags