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 namedVARIABLE_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-envflag, 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
| Action | Code Example | Notes |
|---|---|---|
| Read environment variable | Deno.env.get("VAR_NAME") | Returns string or undefined |
| Check if variable exists | if (Deno.env.get("VAR_NAME")) { ... } | Avoids errors if variable missing |
| Run script with permission | deno run --allow-env script.ts | Required to access env variables |
| Handle missing variable | const 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.