Skip to content

AWS Router: ReferenceError when viewerRequest injection uses await #6331

@charliecode

Description

@charliecode

Using await in edge.viewerRequest.injection breaks access to routerNS inside getRoutes(), throwing ReferenceError: cannot access variable before initialization.

Reproduction

const router = new sst.aws.Router('Router', {
  edge: {
    viewerRequest: {
      injection: `
        await cf.kvs().get('some-key');
      `
    }
  }
});

Make a request that triggers the injected code → Error when getRoutes() accesses routerNS.

Code Structure

The Router component creates CloudFront Function code with this structure:

async function handler(event) {
  ${userInjection}
  ${blockCloudfrontUrlInjection}
  ${CF_ROUTER_INJECTION}

  const routerNS = "${kvNamespace}";

  async function getRoutes() {
    const v = await cf.kvs().get(routerNS + ":routes"); // Error here
  }
  
  const routes = await getRoutes();
}

What Works

  • Moving routerNS declaration inside getRoutes() function → Fixes the error
  • Synchronous injected code (no await) → Works, but no good if you want to exit early

What Doesn't Work

  • Async injected code with await → Breaks routerNS access inside getRoutes()

Error

ReferenceError: cannot access variable before initialization

Occurs when getRoutes() tries to access routerNS. CloudWatch logs show routerNS is declared but inaccessible from inside getRoutes().

Environment

  • SST Version: 3.17.23
  • Node Version: >=22.0.0
  • CloudFront Functions runtime: cloudfront-js-2.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions