Uncaught (in promise) ReferenceError: env is not defined

I’m trying to use the new D1 on my Worker.

I’ve correctly configured and deployed with wrangler adding to my wrangler.toml the

[[ d1_databases ]]
binding = “D1_STORAGE”
database_name = “access_log”
database_id = “5fd10a20-…”

For some reason, when i try to write on it inside the worker with

const { results } = await env.D1_STORAGE.prepare(`
    INSERT INTO access(timestamp, user) VALUES (?, ?)
      `).bind(now_date, psk_db).all();

I got ReferenceError: env is not defined

It would help if you could share your full worker.

Are you using Service Workers, or Module Workers?
With Service Workers (which use global scope & addEventListener), bindings are on the global scope, i.e

addEventListener("fetch", async (event) => {
  let value = await KV.get("to-do:123");
.....

With Module Workers, bindings are on env

export default {
  async fetch(request, env, ctx) {
    let value = await env.KV.get("to-do:123");
.....

Make sure you are using the right format/passing env through.
I believe D1 still only supports Module Workers as well.

You can find a get started guide here:

ps. You might have better luck/easier responses with Workers questions/issues in the Cloudflare Developer Discord, if you need more help, feel free to pop in there, there’s a #d1-open-alpha channel.

1 Like

That’s my full worker.

It checks a specific header and returns the value of a KV with that key

var PRESHARED_AUTH_HEADER_KEY = "X-Custom-PSK";
      var corsHeaders = {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET, OPTIONS",
        "Access-Control-Allow-Headers": "*",
        "content-type": "application/json;charset=UTF-8"
      };
      async function handleRequest(request, env) {
        if (request.method === "OPTIONS") {
          return handleOptions(request);
        }
        const url = new URL(request.url);
        const psk_db = await KV_STORAGE.get(request.headers.get(PRESHARED_AUTH_HEADER_KEY));



        if (psk_db === null) {
          return new Response("Access denied", { status: 404 });
        } else {
          const data = {
            "pswd": psk_db
          };

          json = JSON.stringify(data, null, 2);
        }
        return new Response(json, {
          headers: {
            "content-type": "application/json;charset=UTF-8",
            "Access-Control-Allow-Origin": "*"
          }
        });
      }
      function handleOptions(request) {
        if (request.headers.get("Origin") !== null && request.headers.get("Access-Control-Request-Method") !== null && request.headers.get("Access-Control-Request-Headers") !== null) {
          return new Response(null, {
            headers: corsHeaders
          });
        } else {
          return new Response(null, {
            headers: {
              "Allow": "GET, OPTIONS",
              "content-type": "application/json;charset=UTF-8"
            }
          });
        }
      }
      addEventListener("fetch", (event) => {
        event.respondWith(handleRequest(event.request));
      });
    }
  });

I’m using a Service Workers and I need D1 accesso, not really KV as you have explained (I’m already using KV successfully)

I can’t accept the answer as it does nothing in my case

Thanks for attaching your full worker.
I was just using KV as an example of how you could access a binding on both environments.

env doesn’t exist in service workers, only in module workers.
D1 only works in Module Workers. D1 is a bit hacky right now and only works from wrangler as well, as it needs a shim, and the shim only works with Module Workers, hence the restriction. Perhaps when it goes to General Release, Service workers will be supported.

Module Workers aren’t too different from Service Workers, if you need D1, you can migrate your worker:

(There are other advantages to Module Workers as well, faster start, safer, etc)

Oh, that was the issue. Thanks, I look into it