Tips for resolving the AWS CDK setContext error while updating beyond v1.9.0

Attempting to upgrade AWS CDK code from version 1.9.0 to version 1.152.0, I encountered a problem with the setContext code no longer being valid.

The error message states ‘Cannot set context after children have been added: Tree’

The original code that needs updating is:

const app = new cdk.App();

let stage: string = app.node.tryGetContext('stage');

// AppConfig interface  
// stageConfig variable of custom defined interface, StageConfig
const appConfig: AppConfig = {
  domainName: app.node.tryGetContext('domainName'),
  isProduction: stage === 'prod',
  stageName: stage,
  // default to getting dev config if stage is other than prod or test
  stageConfig: app.node.tryGetContext(stage === 'prod' || stage === 'test' ? stage : 'dev')
};

// set appConfig as a context variable for downstream stacks to use
app.node.setContext('config', appConfig);

The issue seems to be that when defining the app variable, it now requires including the set context data. Thus, app.node.tryGetContext cannot be used because it references the variable being defined.

My attempts to set stage to process.env.STAGE and domainName to process.env.DOMAINNAME always result in 'undefined':

let stage = process.env.STAGE || 'dev';

let app = new cdk.App({
  context: { ['config']: {
    domainName: process.env.DOMAINNAME,
    isProduction: stage === 'prod',
    stageName: stage,
    stageConfig: process.env.STAGE === (stage === 'prod' || stage === 'test' ? stage : 'dev')
  }}
});

Answer №1

As of version 1.9.0, setting context at the App level is no longer possible according to this GitHub issue

To work around this limitation, you can either set context at a construct level or initialize the app with the context as shown in your second example, but please note that you won't be able to reference any existing context variables.

process.env contains your environment variables. If it returns undefined, that means the environment variable does not exist.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating a JavaScript file into Angular

I'm looking to incorporate a new feature from this library on GitHub into my Angular project, which will enhance my ChartJS graph. @ViewChild('myChart') myChart: ElementRef; myChartBis: Chart; .... .... const ctx = this.myChart.nativeEleme ...

Definition for the type react-navigation-v6 <Stack.Group>

I'm having trouble figuring out the proper type definition for a Stack group that includes screens (refer to TestStack.Group and the nested TestStack.Screen). The navigation stack: const TestStack = createNativeStackNavigator<TestStackParamList> ...

Exploring Cypress: Leveraging the Power of Variable Assignment

Recently, I encountered an issue while working with a variable in a Cypress each loop. Despite incrementing the variable within the loop, it resets to zero once outside of it. Can someone shed light on why this happens and suggest a solution? Thank you. p ...

TypeScript seems to be failing to detect the necessary checks before they are used

I've been pondering on how to ensure TypeScript acknowledges that I am verifying the existence of my variables before using them. Below is the code snippet : Here's the function responsible for these checks: function verifyEnvVars(){ if (!proc ...

Typescript is struggling to accurately infer extended types in some cases

My goal is to optimize the body of a NextApiRequest for TypeScript. I currently have this code snippet: // This is a type from a library I've imported export interface NextApiRequest { query: Partial<{ [key: string]: string | string[]; ...

Similar to the "beforesend" functionality in JavaScript, there is a corresponding feature

When attempting to post a comment in my ionic app using the Wordpress api, I encountered error 401 (unauthorized) indicating that the Wordpress api does not recognize me as logged in. This is the code I am using: postComment(params?: any) { let nonce = l ...

Ways to extract a return from an Observable

Do you know how to retrieve the _value from the following code snippet: Here is the function I am referring to: jobsLength(){ const jobslength:any; jobslength=this.searchLogic.items$ console.log(jobslength) }; ...

"Handling dependency injection with cyclic dependencies along with a custom implementation of HTTP and ConfigService

I am currently working on implementing a ConfigService to retrieve the appropriate configuration for each environment within the project. However, I have run into an issue with cyclic dependencies. (index):28 Error: (SystemJS) Provider parse errors: C ...

Unleash the potential of a never-ending expansion for grid cells on Canvas

ts: templateStyle = { display: 'grid', 'grid-template-columns': 'calc(25%-10px) calc(25%-10px) calc(25%-10px) calc(25%-10px)', 'grid-template-rows': '150px auto auto', 'grid-gap ...

How to determine the frequency of a specific word in a sentence using Angular 5

I need help finding a solution to count how many times a word appears in sentences. Input: k = 2 keywords = ["anacell", "cetracular", "betacellular"] reviews = [ "Anacell provides the best services in the city", "betacellular has awesome services", ...

Issue encountered while creating Next.js 13.4 application: The type 'ResolvingMetadata | undefined' does not meet the requirement of 'ResolvingMetadata'

I'm currently working on dynamically generating metadata for my Next.js 13.4 application using this code snippet: export async function generateMetadata( { params, searchParams }: Props, ) { try { // extract the route parameters ...

Error: Loki cannot be used as a constructor

Can anyone assist me in understanding why this code is not functioning correctly? Here's what my index.ts file in Hapi.js looks like: import { Server, Request, ResponseToolkit } from '@hapi/hapi'; import * as Loki from 'lokijs'; ...

Issue with routing during startup of Ionic 4 application

We are currently working on a project using Ionic 4 along with Angular framework. One of the issues we are facing is related to logging into the application. Below is a screenshot illustrating the error: Here is the snippet of my code: import { NgModul ...

TypeScript - Issue with generic function's return type

There exists a feature in typescript known as ReturnType<TFunction> that enables one to deduce the return type of a specific function, like this function arrayOf(item: string): string[] { return [item] } Nevertheless, I am encountering difficulti ...

Prisma Hack: excluding properties in type generation

EDIT hiding fields in the TypeScript definitions may pose a hidden danger: inaccessible fields during development with intellisense, but accidentally sending the full object with "hidden" fields in a response could potentially expose sensitive data. While ...

The jquery methods might encounter an issue with an undefined object

I have been attempting to implement a function that triggers when the user reaches the bottom of the window, but TypeScript is flagging errors and mentioning potential undefined objects related to window.scrollTop(), height(), and document.height(). Even ...

Updating the state in React is causing significant delays

In my React project, I am utilizing the pdf-lib (JS library) for some intensive tasks using async/await. My goal is to update a progress bar by modifying the state. However, when I use setState within a setTimeout, the state changes are not reflected unt ...

Using a click event to target the next div and apply a CSS class using Typescript

I am trying to create a Typescript function that will locate the next div and apply a CSS class to it. Here is what I have attempted: <ul> <li><a href="#" onclick="toggle()">Item 1</a></li> <div class="content hide ...

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

Tips for resolving the setAttribute() function error message: "Argument of type 'boolean' is not assignable to parameter of type 'string'"

I am currently working on a function that dynamically updates the HTML aria-expanded attribute based on whether it is true or false. However, when I declare element as HTMLElement, I encounter an error stating Argument of type 'boolean' is not as ...