dotenv with Angular 19

Discussão em 'Angular' iniciado por pop, Julho 30, 2025.

  1. pop

    pop Guest

    Ater reading the official docs, going through SO and some Medium articles, I still can't figure out how to set up dotenv in such a way that it replaces src/environments/environment.ts variables with the .env vars.

    Let's say I have this environment.ts for local development:

    export const env = {
    someApi: "https://some.tld/api/v1/",
    someApiKey: process.env['SOME_API_KEY']
    }


    I am in the Nx context, so I've added @dotenvx/dotenvx to my dependencies and added three files:

    apps/some_app/.env
    apps/some_app/.env.uat
    apps/some_app/.env.prod


    with the following contents:

    SOME_API_KEY="123-API-456-KEY-789"
    ANOTHER_API_KEY="123-API-456-KEY-789"


    I've also adjusted the package scripts, so they look like this:

    "scripts": {
    "start:some-app": "dotenvx run -f apps/some-app/.env -- nx serve some-app",
    "build:some-app": "dotenvx run -f apps/some-app/.env.prod -- nx build some-app--configuration production",
    "build:some-app:uat": "dotenvx run -f apps/some-app/.env.uat -- nx build some-app--configuration uat",
    "watch:some-app": "nx build some-app--watch --configuration development",
    "test:some-app": "nx test some-app",
    "coverage:some-app": "nx test some-app--no-watch --code-coverage"
    },


    which supposedly runs dotenv script and substitutes the environment placeholders. But I get:

    Uncaught ReferenceError: process is not defined


    instead. What is missing in my setup for dotenv for Angular monorepo?

    Update:

    After adding

    import process from 'process';


    to the environment.ts I now get this error:

    "Uncaught Error: Module "process" has been externalized for browser compatibility. Cannot access "process.env" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details." which does not help a lot, as
    a) I had no idea I had this module in the first place
    b) The troubleshooting guide just forwards me back to "third-party library"
    c) dotenv doesn't seem to have anything on this issue

    I am sorry someone finds this worth a downvote but, really, there is no place to ask these kinds of questions other then SO.

    Continue reading...

Compartilhe esta Página