Skip to content

Reading variables

Your runtime variables are attached to your environment's Worker when a deployment is published, along with Hiraiship's system variables. Code running at the edge reads them from its env, the object Cloudflare Workers pass to every request. A variable available at build only isn't there; see Build variables.

Hono

On the context, as c.env:

src/index.ts
import { Hono } from 'hono';
 
type Bindings = { API_TOKEN: string };
 
const app = new Hono<{ Bindings: Bindings }>();
 
app.get('/', (c) => c.text(c.env.API_TOKEN ? 'configured' : 'missing'));
 
export default app;

Futon

On ctx.runtime.env, when the app is exported with toWinterCgHandler:

src/index.ts
import { Futon, toWinterCgHandler } from '@rasenganjs/futon';
 
type Bindings = { API_TOKEN: string };
 
const app = new Futon<Bindings>();
 
app.get('/', async (ctx) => new Response(ctx.runtime.env.API_TOKEN ? 'configured' : 'missing'));
 
export default { fetch: toWinterCgHandler(app) };

A plain Worker

As the second argument of fetch:

src/index.ts
export default {
  async fetch(request: Request, env: { API_TOKEN: string }) {
    return new Response(env.API_TOKEN ? 'configured' : 'missing');
  },
};

React Router

A server-rendered React Router app reads them from cloudflare:workers, in a loader or an action:

app/routes/home.tsx
import { env } from 'cloudflare:workers';
 
export function loader() {
  return { configured: Boolean(env.API_TOKEN) };
}

TanStack Start

A server-rendered TanStack Start app reads them from cloudflare:workers, in a server function or a server route:

src/routes/status.tsx
import { createServerFn } from '@tanstack/react-start';
import { env } from 'cloudflare:workers';
 
const getConfigured = createServerFn({ method: 'GET' }).handler(async () => Boolean(env.API_TOKEN));

Astro

An Astro page rendered on demand, or an endpoint, reads them from cloudflare:workers:

src/pages/status.astro
---
export const prerender = false;
import { env } from 'cloudflare:workers';
---
<p>{env.API_TOKEN ? 'configured' : 'missing'}</p>

Next.js

A Next.js Server Component rendered on request, or a route handler, reads them from cloudflare:workers:

app/api/status/route.ts
import { env } from 'cloudflare:workers';
 
export function GET() {
  return Response.json({ configured: Boolean(env.API_TOKEN) });
}

Frontends

A static frontend (Vite, a client-rendered Rasengan.js app, a static site) has no code at the edge: its files are served as they are, so it can't read variables at runtime. Values it needs must be in the bundle: make them build variables. Only put values there that anyone may see.

Values are strings

Every variable is a string. Parse numbers and booleans yourself:

const maxItems = Number(env.MAX_ITEMS ?? '20');
const debug = env.DEBUG === 'true';