Search code examples
cloudflarecloudflare-workers

Detecting if we are running in dev mode or in production mode in CloudFlare Worker


I need to know in my worker script if it is running using wrangler dev locally or it is running at cloudflare after wrangelr publish.

Is there an environment variable that tells me that, or a request headers?

Code snippet would be highly appreciated.


Solution

  • There isn't a builtin variable, but you can populate such info yourself by defining environments in your wrangler.toml

    For example, if we say the topmost [vars] are meant to be used in production, we can declare another variable set meant to be used in local environment. (the environment name is irrelevant)

    type = "webpack"
    webpack_config = "webpack.config.js"
    
    # these will be used in production
    vars = { WORKER_ENV = "production", SENTRY_ENABLED = true }
    
    [env.local]
    # these will be used only when --env=local
    vars = { WORKER_ENV = "local", SENTRY_ENABLED = false }
    

    From then on, if you run your worker locally using

    wrangler dev --env=local
    

    the value of binding WORKER_ENV will be populated as defined under [env.local.vars].

    By the way, the syntax of wrangler.toml above is equivalent to

    type = "webpack"
    webpack_config = "webpack.config.js"
    
    [vars]
      WORKER_ENV = "production"
      SENTRY_ENABLED = true
    
    [env]
    
      [env.local]
    
        [env.local.vars]
          WORKER_ENV = "local"
          SENTRY_ENABLED = false
    

    Which I believe it's easier to understand