Import
Runtime Detection
getRuntimeKey
Detect the current JavaScript runtime:Runtime - A string identifying the current runtime
Supported Runtimes
'node'- Node.js'deno'- Deno'bun'- Bun'workerd'- Cloudflare Workers'fastly'- Fastly Compute'edge-light'- Vercel Edge Runtime and similar'other'- Unknown or unsupported runtime
Environment Variables
env
Access environment variables in a runtime-agnostic way:Context
required
The Hono context object
Runtime
Optional runtime override. If not specified, automatically detected using
getRuntimeKey()T & Context['env'] - Object containing environment variables
Type-safe Environment Variables
With Generic Type Parameter
Define environment variable types inline:With Hono Generics
Define environment variables at the application level:Combined Approach
Combine both generic types:Runtime-specific Behavior
Theenv function adapts to different runtimes automatically:
Node.js and Bun
Accessesprocess.env:
Deno
AccessesDeno.env.toObject():
Cloudflare Workers
Accesses environment bindings from context:Fastly Compute
Returns empty object (use ConfigStore instead):Edge Runtime
Accessesprocess.env:
Use Cases
Runtime-specific Configuration
Adjust behavior based on runtime:Database Connection
Connect to database using environment variables:API Keys and Secrets
Access API keys securely:Feature Flags
Implement feature flags with environment variables:Manual Runtime Override
Override automatic runtime detection when needed:Known User Agents
The helper uses user agents for runtime detection:Detection Priority
Runtime detection follows this priority:- Check
navigator.userAgentagainst known user agents - Check for
EdgeRuntimeglobal (Edge Runtime) - Check for
fastlyglobal (Fastly Compute) - Check
process.release.name === 'node'(Node.js) - Return
'other'if none match
Type Definitions
Best Practices
Type Your Environment
Always provide TypeScript types for environment variables to catch errors early
Use Hono Bindings
Define environment types in Hono’s generic
Bindings for better type inferenceValidate Variables
Validate that required environment variables exist before using them
Avoid Runtime Checks
Rely on automatic detection rather than manual runtime checking when possible
For Cloudflare Workers, environment variables are accessed via bindings (
c.env) rather than traditional environment variables. The env helper handles this automatically.