Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use environment variable inside nx project.json

I'm using nx as my monorepo management tool, which contains typescript apis and angular frontends.
Now i'm trying to get my project running inside github codespaces.

Everything works fine except the angular applications, when I try to serve them.
The I get and error Invalid Host/Origin header. This issue can be resolved using the --public-host flag.

This is how I can now server my angular applications using the codespaces environment variable CODESPACE_NAME and nx cli:

npx nx serve application --publicHost=${CODESPACE_NAME}-4080.githubpreview.dev:443

My question is now, if it's possible to configure a new target inside project.json to serve my application like npx nx run application:codespaces?

I already tried to create a new target but it does not resolve the environment variable:

...
 "codespaces": {
  "executor": "@angular-devkit/build-angular:dev-server",
  "configurations": {
    "production": {
      "browserTarget": "console:build:production"
    },
    "development": {
      "browserTarget": "console:build:development"
    }
  },
  "defaultConfiguration": "development",
  "options": {
    "publicHost": "${CODESPACE_NAME}-4080.githubpreview.dev:443",
    "port": 4080
  }
},
...
like image 228
Norbert Bartko Avatar asked Feb 28 '26 22:02

Norbert Bartko


1 Answers

As hinted by @Jonathan, the option strings are not pre-processed by many default executors. Either you can create your own custom executors where you process the options using the environment variable values and customize your application execution.

Example:

import { ExecutorContext } from '@nrwl/devkit';
import { RunCommandExecutorSchema } from './schema';

export default async function runExecutor(
    options: RunCommandExecutorSchema,
    context: ExecutorContext
) {
    console.log('Executor ran for RunCommand', options);

    // process env vars within options
    options = JSON.parse(
        JSON.stringify(options)
            .replace(/\$(\w+)/g, (_, key) => process.env[key] || '')
            .replace(/'/g, '"')
    ) as RunCommandExecutorSchema;

    console.log('Executor ran for RunCommand', options);

    // run @angular-devkit/build-angular:dev-server with this context now
    
    return {
        success: true
    };
}

Btw, if you are using custom run commands, then you will have access to all the environment variables declared in .env file as mentioned in the docs here.

Example:

"echo": {
    "executor": "nx:run-commands",
    "options": {
        "command": "echo $SOME_ENV_VAR",
    }
},
like image 143
Noman Avatar answered Mar 03 '26 10:03

Noman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!