Environment Variables in Deno

 by Robin Wieruch
 - Edit this Post

Environment variables are great for hiding sensitive information about your Deno application. This can be API keys, passwords, or other data which shouldn't be visible to others. That's why there exists the .env file, which you would have to create, to hide sensitive information. We will create this file and pass some sensitive information to it:

PASSWORD=Geheimnis

In your source code files, you can use this environment variable with the dotenv third party library:

import { config } from 'https://deno.land/x/dotenv/mod.ts';
const password = config()['PASSWORD'];
console.log(password);
// "Geheimnis"

The utility function returns an object with all the key/value pairs from the .env file. Now the information isn't exposed in the source code anymore, but only available in the environment variables file.

Once you start your Deno application, you should see a permission error showing up on the command line: "Uncaught PermissionDenied: read access to "/Users/mydspr/Developer/Repos/deno-example", run again with the --allow-read flag". You can allow the access on environment variables with a permission flag in Deno:

deno run --allow-read index.ts

It's important to note that the .env file shouldn't be shared in a public repository where everybody can see it. If you make your source code public, for example on GitHub, consider adding the .env file to a .gitignore file.

Keep reading about 

If you happen to have a custom Webpack setup, you may be wondering how to set up CSS with Webpack. This short tutorial walks you through the process. First of all, you need to install a CSS loader and…

A brief walkthrough on how to upgrade Vite from JavaScript to TypeScript. The tutorial assumes that you have already created a React project with Vite in JavaScript. To use TypeScript in React (with…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.