Skip to content

[BUG] TypeError: A dynamic import callback was not specified when using getCloudflareContext #226

@dandoen

Description

@dandoen

Describe the bug

I am using a service binding in my middleware to let another worker handle authentication. I have configured this as following and this works properly when deployed and when running in preview mode locally.

import { Fetcher } from "@cloudflare/workers-types";

declare module "next/server" {
  interface NextRequest {
    apiClient: ApiClient;
  }
}

export interface Env {
  API: Fetcher;
}

function createApiClient(env: Env) {
  // fetch client using env.API
}

export async function middleware(request: NextRequest) {
  const env = (await getCloudflareContext()).env as Env;
  const apiClient = await createApiClient(env);
  request.apiClient = apiClient;
  
  // Redacted for brevity: check using api client whether user's token is valid. If not return 401
  
  return NextResponse.next();
}

But when in next dev this throws

TypeError: A dynamic import callback was not specified.
image

Steps to reproduce

  1. Use getCloudflareContext in middleware.ts
  2. Run app with next dev
  3. Refresh the page

Expected behavior

No error to be thrown

@opennextjs/cloudflare version

experimental

Wrangler version

3.99.0

next info output

pnpm next info

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.0.0: Fri Sep 15 14:41:43 PDT 2023; root:xnu-10002.1.13~1/RELEASE_ARM64_T6000
  Available memory (MB): 65536
  Available CPU cores: 10
Binaries:
  Node: 22.12.0
  npm: 10.9.0
  Yarn: N/A
  pnpm: 9.15.0
Relevant Packages:
  next: 14.2.5 // An outdated version detected (latest is 15.1.3), upgrade is highly recommended!
  eslint-config-next: 15.0.3
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 5.7.2


### Additional context

_No response_

Metadata

Metadata

Labels

bugSomething isn't working

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions