Angular icon Get $100 off the 7-Courses Angular Master Bundle!

See the bundle then add to cart and your discount is applied.


Handling .env variables in Deno

May 23, 2020 2 mins read

Deno post

In this post you’ll learn how to use environment variables (.env) in Deno!

If you’ve also used Node.js before, this post will show you how to do it the Deno way.

What is the .env file?

The .env file is for keeping all your secrets, that means anything from a password to private or public API keys and more.

Typically we’d do something like this:

// .env

🍭 The .env file lives in the root of your project and should not be checked into version control - locally create it and add it to your .gitignore!

.env in Node.js

Coming from a Node.js background, we’d then expect to access our variables such as FIREBASE_API_KEY from the magical process.env variable:

import { config } from 'dotenv';

const firebaseKey = process.env.FIREBASE_API_KEY;
const stripeKey = process.env.STRIPE_API_KEY;

To supply custom environment variables would either use an inline script such as NODE_ENV=dev node app.js or use the dotenv package and call config() to bring our custom variables in.

They’d then be available as process.env.<VARIABLE>.

.env in Deno

In Deno, it feels a bit nicer as we can import config and simply call it:

import { config } from "";

const env = config();

console.log(env.FIREBASE_API_KEY); // 'XYZDEF123987...'
console.log(env.STRIPE_API_KEY); // '56780987ABCQWERTY...'

Our env variable contains the value returned from the config() call - an object with our variables as keys 🔑.

Or better yet with ES6 object destructuring:

import { config } from "";

const { FIREBASE_API_KEY, STRIPE_API_KEY } = config();

console.log(FIREBASE_API_KEY); // 'XYZDEF123987...'
console.log(STRIPE_API_KEY); // '56780987ABCQWERTY...'

We also benefit from not having a node_modules folder anymore, with Deno all dependencies are hosted elsewhere and not locally. This will surely make a lot of developers happier and reduces the complexities dealing with local dependencies - especially across projects and teams.

It’s recommended by the Deno authors to use Safe Mode in Deno. Alongside our existing code, here’s how we can add it:

// Deno example
import { config } from "";

const { FIREBASE_API_KEY, STRIPE_API_KEY } = config({ safe: true });

console.log(FIREBASE_API_KEY); // 'XYZDEF123987...'
console.log(STRIPE_API_KEY); // '56780987ABCQWERTY...'

Safe mode in Deno will produce an error if an environment variable is missing, we don’t want our entire app burning in production do we? Enable it!

🕵️‍♀️ Check out the full documentation on Environment Variables in Deno which contains more information on additional options you can use.

This was a quick getting started post for those interested in learning Deno coming from a Node.js background on how to setup your environment variables using the .env file in Deno!

Happy coding!

You'll also like...