Deployment Fails with @sveltejs/adapter-cloudflare

I am attempting to deploy to CloudFlare Page and I believe I need some help setting up my environment. My local environment is setup using Miniflare where I set the platform variable, here is what my hooks.server.ts file looks like:

export const handle: Handle = async ({ event, resolve }) => {
  if (dev) {
    const mf = await import('./lib/server/miniflare');
    event.platform = await mf.setupPlatform();
  }

  event.locals.db = getDB(event.platform!.env.DB);
  event.locals.auth = getAuth(event.platform!.env.DB).handleRequest(event);

  return await resolve(event);
};


I am using drizzle-orm and lucia-auth for this project. Here are some function definitions function getDB(db: D1Database) => DrizzleD1Database and function getAuth(db: D1Database) => AuthRequest (AuthRequest is a lucia type), however I don't think they are the issue, because it works just fine in my development environment with Miniflare.

Here is what my app.d.ts file looks like:
/// <reference types="@sveltejs/adapter-cloudflare" />

declare global {
  namespace App {
    interface Locals {
      auth: import("lucia").AuthRequest;
      db: import('drizzle-orm/d1').DrizzleD1Database<typeof import('$lib/schema')>;
    }
    interface Platform {
      env: {
        DB: D1Database;
        KV: KVNamespace;
        DOCS: R2Bucket;
      };
      context: {
        waitUntil(promise: Promise<any>): void;
      };
      caches: CacheStorage & { default: Cache };
      cf?: IncomingRequestCfProperties;
    }
  }

  namespace Lucia {
    type Auth = import("$lib/server/lucia").Auth;
    type DatabaseUserAttributes = {
       // ...
    };
    type DatabaseSessionAttributes = {};
  }
}

export {};


When I build and attempt to deploy the build it says the event.platform is undefined:
12:52:36.928    > Using @sveltejs/adapter-cloudflare
12:52:38.216    TypeError: Cannot read properties of undefined (reading 'env')
12:52:38.216        at Object.handle (file:///opt/buildhome/repo/.svelte-kit/output/server/chunks/hooks.server.js:34:42)
...

Deployment ID - 55b93723-6495-4000-bfb4-f3e971753c60

I have search Google for an answer to my problem, but I haven't been able to find anyone else who is having the same problem with platform being undefined in a SvelteKit hooks.server.ts file. I have added the DB, KV and DOCS bindings from the workers dashboard, however I don't think that is the problem as well, because the error shows that the event.platform variable is undefined.

Hopefully I have enough information in this post. Any help is appreciated!
Was this page helpful?