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
Using
awaitinedge.viewerRequest.injectionbreaks access torouterNSinsidegetRoutes(), throwingReferenceError: cannot access variable before initialization.Reproduction
Make a request that triggers the injected code → Error when
getRoutes()accessesrouterNS.Code Structure
The Router component creates CloudFront Function code with this structure:
What Works
routerNSdeclaration insidegetRoutes()function → Fixes the errorawait) → Works, but no good if you want to exit earlyWhat Doesn't Work
await→ BreaksrouterNSaccess insidegetRoutes()Error
Occurs when
getRoutes()tries to accessrouterNS. CloudWatch logs showrouterNSis declared but inaccessible from insidegetRoutes().Environment