by Sai gowtham

How to use environment variables in Deno

In this tutorial, we are going to learn about how to use the environment variables with .env file in Deno.

Environment variables

Environment variables are used to hide important information about your Deno app to public users. Such as API Secret keys, passwords and, app URLs, etc.

Defining environment variables

To define environment variables, we need to create a new file called .env in our root deno app folder.

Now, add the following environment variables to the .env file.

.env
MY_API_KEY=YEUU93YHGDM
MY_API=https://api.example.com/v2/users

In the above code, we have defined two environment variables by using key=value pairs.

Note: Don’t commit .env file to a public GitHub repository, add it to a .gitignore file to avoid accidental commits.

Accessing the environment variables

To access the environment variables inside the deno app files, we need to import the config function and invoke it.

app.js
import { config } from 'https://deno.land/x/dotenv/mod.ts';

const env = config();

console.log(env.MY_API_KEY); // YEUU93YHGDM
console.log(env.MY_API); // https://api.example.com/v2/users

The config() function returns an object with key/value pairs we defined in .env file

To run your app without any errors, you need to allow read access to a deno process by using --allow-read flag.

➜  deno run --allow-read app.js

YEUU93YHGDM
https://api.example.com/v2/users

Or you can use es6 object destructuring.

app.js
import { config } from 'https://deno.land/x/dotenv/mod.ts';

const {MY_API_KEY, MY_API_KEY} = config();

console.log(MY_API_KEY); // YEUU93YHGDM
console.log(MY_API); // https://api.example.com/v2/users

Auto loading

The load.ts module helps us to automatically load the local .env file to a deno process.

Example:

app.js
import "https://deno.land/x/dotenv/load.ts";

console.log(Deno.env.get("MY_API_KEY"));
console.log(Deno.env.get("MY_API"));
➜ deno --allow-env --allow-read app.js
YEUU93YHGDM
https://api.example.com/v2/users

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course