How to Use Deno.env to Access Environment Variables
Use
Deno.env.get("VARIABLE_NAME") to read environment variables in Deno. You can also set variables with Deno.env.set("VARIABLE_NAME", "value") and list all variables with Deno.env.toObject(). Remember to run your script with --allow-env permission.Syntax
Deno.env is an object that provides methods to interact with environment variables.
Deno.env.get(name: string): string | undefined- Gets the value of an environment variable by name.Deno.env.set(name: string, value: string): void- Sets or updates an environment variable.Deno.env.delete(name: string): void- Deletes an environment variable.Deno.env.toObject(): Record<string, string>- Returns all environment variables as an object.
All these methods require the --allow-env flag when running your Deno script.
typescript
const value = Deno.env.get("MY_VAR"); Deno.env.set("MY_VAR", "newValue"); Deno.env.delete("MY_VAR"); const allVars = Deno.env.toObject();
Example
This example shows how to read, set, and list environment variables using Deno.env. Run the script with deno run --allow-env script.ts.
typescript
console.log("Original MY_VAR:", Deno.env.get("MY_VAR")); Deno.env.set("MY_VAR", "HelloDeno"); console.log("Updated MY_VAR:", Deno.env.get("MY_VAR")); console.log("All environment variables:", Deno.env.toObject());
Output
Original MY_VAR: undefined
Updated MY_VAR: HelloDeno
All environment variables: { ... all current env vars including MY_VAR: 'HelloDeno' ... }
Common Pitfalls
- Not running the script with
--allow-envwill cause a permission error. - Trying to get a variable that does not exist returns
undefined, so always check before using. - Environment variables are always strings; convert them if you expect other types.
typescript
try { const secret = Deno.env.get("SECRET_KEY"); if (!secret) { console.log("SECRET_KEY is not set."); } else { console.log("Secret key is", secret); } } catch (error) { console.error("Permission denied. Run with --allow-env flag."); }
Quick Reference
| Method | Description | Requires --allow-env |
|---|---|---|
| Deno.env.get(name) | Get environment variable value | Yes |
| Deno.env.set(name, value) | Set or update variable | Yes |
| Deno.env.delete(name) | Remove variable | Yes |
| Deno.env.toObject() | Get all variables as object | Yes |
Key Takeaways
Always run Deno scripts accessing environment variables with --allow-env permission.
Use Deno.env.get() to safely read environment variables as strings or undefined.
Set or update variables with Deno.env.set() during runtime if needed.
Check for undefined to avoid errors when variables are missing.
Use Deno.env.toObject() to get a snapshot of all environment variables.