0
0
DenoHow-ToBeginner ยท 3 min read

How to Read Environment Variables in Deno

In Deno, you can read environment variables using Deno.env.get("VARIABLE_NAME"). This method returns the value as a string or undefined if the variable is not set.
๐Ÿ“

Syntax

The syntax to read an environment variable in Deno is simple:

  • Deno.env.get("VARIABLE_NAME"): Retrieves the value of the environment variable named VARIABLE_NAME.
  • If the variable does not exist, it returns undefined.

You must run your Deno script with the --allow-env flag to allow access to environment variables for security reasons.

typescript
const value = Deno.env.get("MY_VAR");
console.log(value);
๐Ÿ’ป

Example

This example shows how to read an environment variable named MY_VAR and print its value. Run the script with the environment variable set and the --allow-env flag.

typescript
const myVar = Deno.env.get("MY_VAR");
if (myVar) {
  console.log(`MY_VAR is: ${myVar}`);
} else {
  console.log("MY_VAR is not set.");
}
Output
MY_VAR is: hello_world
โš ๏ธ

Common Pitfalls

Common mistakes when reading environment variables in Deno include:

  • Not running the script with the --allow-env flag, which causes a permission error.
  • Assuming the variable always exists without checking for undefined.
  • Trying to read environment variables without handling the possibility of missing values.
typescript
try {
  // Wrong: missing --allow-env flag will cause error
  const secret = Deno.env.get("SECRET");
  console.log(secret);
} catch (error) {
  console.error("Permission denied. Run with --allow-env flag.");
}

// Correct way with check
const secret = Deno.env.get("SECRET");
if (secret === undefined) {
  console.log("SECRET is not set.");
} else {
  console.log(`SECRET is: ${secret}`);
}
๐Ÿ“Š

Quick Reference

ActionCode ExampleNotes
Read environment variableDeno.env.get("VAR_NAME")Returns string or undefined
Check if variable existsif (Deno.env.get("VAR_NAME")) { ... }Avoids errors if variable missing
Run script with permissiondeno run --allow-env script.tsRequired to access env variables
Handle missing variableconst val = Deno.env.get("VAR_NAME") ?? "default"Use default if undefined
โœ…

Key Takeaways

Use Deno.env.get("VARIABLE_NAME") to read environment variables in Deno.
Always run your script with the --allow-env flag to access environment variables.
Check if the returned value is undefined before using it to avoid errors.
Provide default values or handle missing variables gracefully.
Environment variables are strings; convert them if needed.