DocsPluginsShowcaseReleases
npmStar us on GitHub

Getting Started

IntroductionInstallationProject StructureLayouts and PagesLinking and Navigating

Routing

Folder-Based RoutingFile-Based RoutingDynamic RoutesParallel RoutesIntercepting RoutesCatch-All RoutesMDX & Markdown Pages

Special Files

Loading UIError BoundariesTemplateDefaultNot Found

Data Fetching

LoadersActionsAccessing Route Data

Metadata

Metadata & SEOOpen Graph & TwitterIcons & Favicons

API Routes

API Routes OverviewPlain Function HandlersHono IntegrationDynamic API Routes

Environment Variables

OverviewPrefixes & Client ExposureUsing in API Routes

Styling

CSS OverviewTailwind CSSCSS Modules

Platforms

WebWindowsmacOSLinuxAndroidiOS

Deployment

Deployment OverviewProduction ServerStatic ExportHosting Providers

A native React framework for building cross-platform applications from a single codebase.

Resources

  • Documentation
  • Plugins
  • Showcase
  • Releases

Community

  • GitHub Discussions
  • Reddit
  • Discord
  • LinkedIn

More

  • npm
  • GitHub
  • Issues
  • License

© 2026 Bini Cooperation.

Using Environment Variables in API Routes

Read environment variables in API routes with getEnv and requireEnv.

Overview

In API routes, environment variables are read with getEnv(c, key) and requireEnv(c, key). Both read from the Hono request context, so the same code works on every runtime: Node.js, Bun, Deno, Vercel Edge, Netlify Edge, and Cloudflare Workers.

Always pass c explicitly. No casts are needed - getEnv and requireEnv accept the Hono context type natively. Every read is request-scoped, so there is no process.env fallback to worry about.

Basic Usage

app
api
ƒhello.ts
ƒemail.ts
ƒconfig.ts
/api/hello
/api/email
/api/config
src/app/api/hello.ts
// src/app/api/hello.ts
import { Hono } from 'hono'
import { getEnv, requireEnv } from 'bini-env'

const app = new Hono()

app.get('/hello', (c) => {
  try {
    // requireEnv throws if the var is missing - fail fast on required config
    const apiKey = requireEnv(c, 'MY_API_KEY')

    // getEnv returns undefined if missing - use ?? to provide a default
    const appName = getEnv(c, 'APP_NAME') ?? 'World'
    const timeout = parseInt(getEnv(c, 'TIMEOUT_MS') ?? '5000')

    return c.json({ message: `Hello, ${appName}!` })
  } catch (error: any) {
    if (error.message?.includes('[bini-env] Missing required')) {
      return c.json({ error: error.message }, 500)
    }
    return c.json({ error: 'Something went wrong.' }, 500)
  }
})

export default app

Required vs Optional

Use requireEnv for variables your app cannot run without. Use getEnv with ?? for optional configuration.

src/app/api/example.ts
// src/app/api/example.ts
import { Hono } from 'hono'
import { getEnv, requireEnv } from 'bini-env'

const app = new Hono()

app.post('/example', async (c) => {
  try {
    // Required vars - handler throws immediately if missing
    const dbUrl = requireEnv(c, 'DATABASE_URL')
    const apiKey = requireEnv(c, 'STRIPE_SECRET_KEY')

    // Optional vars - fall back to sensible defaults
    const model = getEnv(c, 'AI_MODEL') ?? 'gpt-4o'
    const region = getEnv(c, 'AWS_REGION') ?? 'us-east-1'
    const maxRetries = parseInt(getEnv(c, 'MAX_RETRIES') ?? '3')
    const debug = getEnv(c, 'DEBUG_MODE') === 'true'

    return c.json({ model, region, maxRetries, debug })
  } catch (error: any) {
    if (error.message?.includes('[bini-env] Missing required')) {
      return c.json({ error: error.message }, 500)
    }
    return c.json({ error: 'Something went wrong.' }, 500)
  }
})

export default app
FunctionUse forBehavior
requireEnv(c, key)Required config - app cannot run withoutThrows if missing or empty
getEnv(c, key) ?? defaultOptional config - fallback to defaultReturns undefined if missing

Complete Example

A full API endpoint that uses environment variables for configuration:

src/app/api/email.ts
// src/app/api/email.ts
import { Hono } from 'hono'
import { getEnv, requireEnv } from 'bini-env'
import nodemailer from 'nodemailer'

const app = new Hono()

app.post('/email/send', async (c) => {
  try {
    const smtpHost = requireEnv(c, 'SMTP_HOST')
    const smtpUser = requireEnv(c, 'SMTP_USER')
    const smtpPass = requireEnv(c, 'SMTP_PASS')
    const fromEmail = requireEnv(c, 'FROM_EMAIL')

    const smtpPort = parseInt(getEnv(c, 'SMTP_PORT') ?? '587')
    const secure = getEnv(c, 'SMTP_SECURE') === 'true'
    const debug = getEnv(c, 'DEBUG_MODE') === 'true'
    const appName = getEnv(c, 'APP_NAME') ?? 'Bini.js App'

    const transporter = nodemailer.createTransport({
      host: smtpHost,
      port: smtpPort,
      secure,
      auth: { user: smtpUser, pass: smtpPass },
      debug,
    })

    const { to, subject, text } = await c.req.json()

    if (!to || !subject || !text) {
      return c.json({ error: 'Missing required fields: to, subject, text' }, 400)
    }

    await transporter.sendMail({
      from: fromEmail,
      to,
      subject: `[${appName}] ${subject}`,
      text,
    })

    return c.json({
      success: true,
      message: 'Email sent',
      from: fromEmail,
      app: appName,
    })
  } catch (error: any) {
    if (error.message?.includes('[bini-env] Missing required')) {
      return c.json({ error: error.message }, 500)
    }
    console.error('Email error:', error)
    return c.json({ error: 'Failed to send email.' }, 500)
  }
})

export default app

Error Handling

Always handle errors from requireEnv gracefully:

src/app/api/config.ts
// src/app/api/config.ts
import { Hono } from 'hono'
import { requireEnv } from 'bini-env'

const app = new Hono()

app.get('/config', async (c) => {
  try {
    const apiKey = requireEnv(c, 'API_KEY')
    const secret = requireEnv(c, 'SECRET_TOKEN')

    return c.json({ configured: true })
  } catch (error: any) {
    if (error.message?.includes('[bini-env] Missing required')) {
      return c.json(
        {
          error: 'Configuration error',
          details: error.message,
        },
        500
      )
    }

    return c.json({ error: 'Something went wrong' }, 500)
  }
})

export default app

On failure, the terminal shows:

>_Terminal
[bini-env] error  Missing required environment variable: "API_KEY"
  -> Set it in your platform's env config or hosting dashboard.

Production Notes

  • Set vars in production - .env files are only loaded during development. In production, set variables in your hosting platform's dashboard.
  • No platform-specific code - getEnv and requireEnv work 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 the BINI_ prefix for client-side public config. No prefix for server-only secrets.
The same API code runs unchanged across all platforms. The environment functions read from the correct source on every platform automatically.

Environment Variables

Overview of getEnv and requireEnv.

Prefixes & Client Exposure

What gets bundled and what stays server-side.

API Routes Overview

Files under app/api/ map to /api/*.

Hono Integration

Routing, middleware, and validation with Hono.

Was this helpful?
PreviousPrefixes & Client Exposure
NextCSS Overview

On this page

  • Overview
  • Basic Usage
  • Required vs Optional
  • Complete Example
  • Error Handling
  • Production Notes
Edit this page on GitHub

Using Environment Variables in API Routes

Read environment variables in API routes with getEnv and requireEnv.

Overview

In API routes, environment variables are read with getEnv(c, key) and requireEnv(c, key). Both read from the Hono request context, so the same code works on every runtime: Node.js, Bun, Deno, Vercel Edge, Netlify Edge, and Cloudflare Workers.

Always pass c explicitly. No casts are needed - getEnv and requireEnv accept the Hono context type natively. Every read is request-scoped, so there is no process.env fallback to worry about.

Basic Usage

app
api
ƒhello.ts
ƒemail.ts
ƒconfig.ts
/api/hello
/api/email
/api/config
src/app/api/hello.ts
// src/app/api/hello.ts
import { Hono } from 'hono'
import { getEnv, requireEnv } from 'bini-env'

const app = new Hono()

app.get('/hello', (c) => {
  try {
    // requireEnv throws if the var is missing - fail fast on required config
    const apiKey = requireEnv(c, 'MY_API_KEY')

    // getEnv returns undefined if missing - use ?? to provide a default
    const appName = getEnv(c, 'APP_NAME') ?? 'World'
    const timeout = parseInt(getEnv(c, 'TIMEOUT_MS') ?? '5000')

    return c.json({ message: `Hello, ${appName}!` })
  } catch (error: any) {
    if (error.message?.includes('[bini-env] Missing required')) {
      return c.json({ error: error.message }, 500)
    }
    return c.json({ error: 'Something went wrong.' }, 500)
  }
})

export default app

Required vs Optional

Use requireEnv for variables your app cannot run without. Use getEnv with ?? for optional configuration.

src/app/api/example.ts
// src/app/api/example.ts
import { Hono } from 'hono'
import { getEnv, requireEnv } from 'bini-env'

const app = new Hono()

app.post('/example', async (c) => {
  try {
    // Required vars - handler throws immediately if missing
    const dbUrl = requireEnv(c, 'DATABASE_URL')
    const apiKey = requireEnv(c, 'STRIPE_SECRET_KEY')

    // Optional vars - fall back to sensible defaults
    const model = getEnv(c, 'AI_MODEL') ?? 'gpt-4o'
    const region = getEnv(c, 'AWS_REGION') ?? 'us-east-1'
    const maxRetries = parseInt(getEnv(c, 'MAX_RETRIES') ?? '3')
    const debug = getEnv(c, 'DEBUG_MODE') === 'true'

    return c.json({ model, region, maxRetries, debug })
  } catch (error: any) {
    if (error.message?.includes('[bini-env] Missing required')) {
      return c.json({ error: error.message }, 500)
    }
    return c.json({ error: 'Something went wrong.' }, 500)
  }
})

export default app
FunctionUse forBehavior
requireEnv(c, key)Required config - app cannot run withoutThrows if missing or empty
getEnv(c, key) ?? defaultOptional config - fallback to defaultReturns undefined if missing

Complete Example

A full API endpoint that uses environment variables for configuration:

src/app/api/email.ts
// src/app/api/email.ts
import { Hono } from 'hono'
import { getEnv, requireEnv } from 'bini-env'
import nodemailer from 'nodemailer'

const app = new Hono()

app.post('/email/send', async (c) => {
  try {
    const smtpHost = requireEnv(c, 'SMTP_HOST')
    const smtpUser = requireEnv(c, 'SMTP_USER')
    const smtpPass = requireEnv(c, 'SMTP_PASS')
    const fromEmail = requireEnv(c, 'FROM_EMAIL')

    const smtpPort = parseInt(getEnv(c, 'SMTP_PORT') ?? '587')
    const secure = getEnv(c, 'SMTP_SECURE') === 'true'
    const debug = getEnv(c, 'DEBUG_MODE') === 'true'
    const appName = getEnv(c, 'APP_NAME') ?? 'Bini.js App'

    const transporter = nodemailer.createTransport({
      host: smtpHost,
      port: smtpPort,
      secure,
      auth: { user: smtpUser, pass: smtpPass },
      debug,
    })

    const { to, subject, text } = await c.req.json()

    if (!to || !subject || !text) {
      return c.json({ error: 'Missing required fields: to, subject, text' }, 400)
    }

    await transporter.sendMail({
      from: fromEmail,
      to,
      subject: `[${appName}] ${subject}`,
      text,
    })

    return c.json({
      success: true,
      message: 'Email sent',
      from: fromEmail,
      app: appName,
    })
  } catch (error: any) {
    if (error.message?.includes('[bini-env] Missing required')) {
      return c.json({ error: error.message }, 500)
    }
    console.error('Email error:', error)
    return c.json({ error: 'Failed to send email.' }, 500)
  }
})

export default app

Error Handling

Always handle errors from requireEnv gracefully:

src/app/api/config.ts
// src/app/api/config.ts
import { Hono } from 'hono'
import { requireEnv } from 'bini-env'

const app = new Hono()

app.get('/config', async (c) => {
  try {
    const apiKey = requireEnv(c, 'API_KEY')
    const secret = requireEnv(c, 'SECRET_TOKEN')

    return c.json({ configured: true })
  } catch (error: any) {
    if (error.message?.includes('[bini-env] Missing required')) {
      return c.json(
        {
          error: 'Configuration error',
          details: error.message,
        },
        500
      )
    }

    return c.json({ error: 'Something went wrong' }, 500)
  }
})

export default app

On failure, the terminal shows:

>_Terminal
[bini-env] error  Missing required environment variable: "API_KEY"
  -> Set it in your platform's env config or hosting dashboard.

Production Notes

  • Set vars in production - .env files are only loaded during development. In production, set variables in your hosting platform's dashboard.
  • No platform-specific code - getEnv and requireEnv work 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 the BINI_ prefix for client-side public config. No prefix for server-only secrets.
The same API code runs unchanged across all platforms. The environment functions read from the correct source on every platform automatically.

Environment Variables

Overview of getEnv and requireEnv.

Prefixes & Client Exposure

What gets bundled and what stays server-side.

API Routes Overview

Files under app/api/ map to /api/*.

Hono Integration

Routing, middleware, and validation with Hono.

Was this helpful?
PreviousPrefixes & Client Exposure
NextCSS Overview

On this page

  • Overview
  • Basic Usage
  • Required vs Optional
  • Complete Example
  • Error Handling
  • Production Notes
Edit this page on GitHub