Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use cloudflare worker env outside fetch scope

I'm creating a cache-proxy with Cloudflare Workers. I'm using a self made class instance to abstract Airtable queries, that require couple of secrets to be instantiated.

Now I must instantiate it inside fetch every time, as it's the only way I know to access Cloudflare env variables. Is there a way to globally access them so I can instantiate the class outside the fetch scope?

import { useAirtable } from 'painless-airtable';
import router from './router';
import type { Env } from './types';

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {

    // I'd like to extract this out of fetch
    const { AIRTABLE_BASE: base, AIRTABLE_TOKEN: token } = env;
    const airtable = useAirtable({ base, token });

    return router.handle(request, { airtable, env, ctx });
  },
};

like image 381
markusand Avatar asked Aug 07 '26 05:08

markusand


1 Answers

Update in 2025: You can now use

import { env } from "cloudflare:workers";

See Import `env` to access bindings in your Worker's global scope

like image 150
MCO Avatar answered Aug 09 '26 18:08

MCO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!