How toGenerate Cloudflare environment type with wrangler
If you're using wrangler to build app deployed to Cloudflare, there's a handy command this tool gives you that can generate a .d.ts file with all your .dev.vars and bindings configured in wrangler.toml.
wrangler types --env-interface RuntimeEnv ./types/cf.d.ts
The --env-interface RuntimeEnv option will set the name of the interface created and ./types/cf.d.ts is the file where it should be saved.
Let's say you have a .dev.vars like this:
.dev.vars SESSION_SECRET="s3cr3t"
And a wrangler.toml like this:
name = "app-name"
[[d1_databases]]
binding = "DB"
database_name = "YOUR DATABASE NAME"
database_id = "YOUR DATABASE ID"
After running the command you will get this file:
types/cf.d.ts // Generated by Wrangler on <DATE> // by running `wrangler types --env-interface RuntimeEnv ./types/cf.d.ts` interface RuntimeEnv { SESSION_SECRET: string; DB: D1Database; }
This can then be used inside your app to type what your Cloudflare Pages and Workers receive from the context.
Do you like my content?
Your sponsorship helps me create more tutorials, articles, and open-source tools.