Using Environment Variables in API Routes
Learn how to read environment variables in your API routes using getEnv and requireEnv.
Overview
In API routes, environment variables are read using getEnv(ctx, key) and requireEnv(ctx, key). Both are auto-imported in API routes and read from the Hono request context via hono/adapter.
const ctx = c as any, then use ctx throughout. No process.env fallbacks — every read is request-scoped.Basic Usage
Required vs Optional
Use requireEnv for variables your app cannot run without. Use getEnv with ?? for optional configuration.
| Function | Use for | Behavior |
|---|---|---|
| requireEnv(ctx, key) | Required config — app cannot run without | Throws if missing or empty |
| getEnv(ctx, key) ?? default | Optional config — fallback to default | Returns undefined if missing |
Complete Example
A full API endpoint that uses environment variables for configuration:
Error Handling
Always handle errors from requireEnv gracefully:
On failure, the terminal shows:
Production Notes
- •Set vars in production —
.envfiles are only loaded during development. In production, set variables in your hosting platform's dashboard. - •No platform-specific code —
getEnvandrequireEnvwork on Node.js, Bun, Deno, Vercel Edge, Netlify Edge, and Cloudflare Workers. - •Never expose secrets — Never return secret values in API responses. Only return configuration status.
- •Use BINI_ for client vars — Use
BINI_prefix for client-side public config. No prefix for server-only secrets.