Skip to content
Theme:

Node.js with native support for .env files — you may not need dotenv anymore

The dotenv package is the most popular way to load environment variables from a .env file in the Node.js ecosystem. From now on, you may not need it anymore. Node v20.6.0 comes with native support for .env configuration files.

A storage mechanism for key/value vars is handy, but we can also use it to configure the runtime via NODE_OPTIONS. This method is a lot easier to manage than long scripts in the package.json file.

Here is a simple example of invoking a node script with the new --env-file flag.

# config.env

NODE_OPTIONS='--title="Testing Node v20.6.0"'
USER_NAME='Paweł Grzybek'
// index.js

console.log(process.title);
console.log(`Hi ${process.env.USER_NAME} 👋`);
node --env-file=config.env index.js

Testing Node v20.6.0
Hi Paweł Grzybek 👋

Comments

  • s
    sergey

    Can you add dark theme for this site? :)

    👆 you can use Markdown here

    Your comment is awaiting moderation. Thanks!
    • Pawel Grzybek
      Pawel Grzybek

      Ah, there is one. It changes according to the operating system's appearance preferences.

      👆 you can use Markdown here

      Your comment is awaiting moderation. Thanks!
      • s
        sergey

        Thank you! It works!

        👆 you can use Markdown here

        Your comment is awaiting moderation. Thanks!
  • C
    Clement Deryckx

    Hi there and thank you for the post. While using typescript and ts-node, it throw an error : Error: Unknown or unexpected option: --env-file. So i guess this is still not fully implemented in all tools we use.

    Otherwise, it works perfectly with the classic node command.

    👆 you can use Markdown here

    Your comment is awaiting moderation. Thanks!
    • Pawel Grzybek
      Pawel Grzybek

      Highly possible if you execute it directly using ts-node CLI. There is a hope though — try executing it using node and a ts-node loader. It may work 🤷‍♂️ Like so:

      node --env-file=config.env --loader ts-node/esm index.ts
      

      👆 you can use Markdown here

      Your comment is awaiting moderation. Thanks!

Leave a comment

👆 you can use Markdown here

Your comment is awaiting moderation. Thanks!