Worker Code Not Finding Environment Variable

Hello -
I’m very new to trying to use Workers in Cloudflare and I’m having an issue where the code I’m using isn’t recognizing the environment variable I created under Settings.

Basically, I’m trying to use a Worker to front an Azure blob store with a SAS token enabled. I’m following a blog entry I found that explained how to do this and provided the code to include in the Worker config - Using Cloudflare to serve your private Azure Storage Blobs · Elio Struyf

The code in my worker is:

addEventListener(‘fetch’, event => {
event.respondWith(handleRequest(event.request))
})
/**

  • Respond to the request
  • @param {Request} request
    */
    async function handleRequest(request) {
    return fetch(${request.url}${SASTOKEN});
    }

I have SASTOKEN defined under Settings - Variables in my worker.

When I’m in the edit code screen, I get a message that says “cannot find name SASTOKEN”.
I’m sure that I’m missing something but, for the life of me, I can’t seem to figure out what it is.

Any pointers on how to sort this out would be much appreciated.

Thanks,
Robin

Hi @robin.hailey ,

Including the env parameter:

It seems that you are not sending the env parameter to your handleRequest function. It is required to access the environment variables as you can see in this example from our official documentation: Environment variables.

export default {
  async fetch(request, env, ctx) {
    return new Response(`API host: ${env.API_HOST}`);
  }
}

So as you can see, after you send the env param, you can call your Environment Variable like this:

return fetch(`${request.url}${env.SASTOKEN}` );

I’m not great at coding, but I hope this information helps, if you have any other questions, I highly suggest you checking our Discord channel, where you will find a lot of talented programmers that will be glad to help you with your Worker.

1 Like

Thanks Luis. I had seen that but, hadn’t been able to make it work for me either.
In the ‘return fetch’ line, the editor complains that ‘env’ (in the env.SASTOKEN) isn’t found. And, even trying to save the changes, I get an error around the ‘export default’ line and it doesn’t save.

Anyway, thanks for the information. I’m sure I’m still doing something wrong - I’ll try out the Discord channel and see if someone can assist.

Thanks,
Robin

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.