Skip to content

How to use ngx env in an angular application that uses SSR #143

@Oussemasahbeni

Description

@Oussemasahbeni

I am using ngx-env with a new Angular v20 project with SSR enabled inside an NX monorepo, and I'm running into a common SSR issue where browser-specific code and environment variable access fails on the server.
My goal is to configure a third-party library (keycloak-angular) using environment variables. My configuration code looks like this:

import {
    AutoRefreshTokenService,
    createInterceptorCondition,
    INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG,
    IncludeBearerTokenCondition,
    provideKeycloak,
    UserActivityService,
    withAutoRefreshToken,
} from 'keycloak-angular';

const backendUrl = import.meta.env.NG_APP_API_URL;

const backendUrlPattern = new RegExp(`^${backendUrl}/?.*$`, 'i');
const urlCondition = createInterceptorCondition<IncludeBearerTokenCondition>({
    urlPattern: backendUrlPattern,
});

export const provideKeycloakAngular = () =>
    provideKeycloak({
        config: {
            realm: import.meta.env.NG_APP_KEYCLOAK_REALM,
            url: import.meta.env.NG_APP_KEYCLOAK_BASE_URL,
            clientId: import.meta.env.NG_APP_KEYCLOAK_CLIENT_ID,
        },
        initOptions: {
            onLoad: 'check-sso',
            silentCheckSsoRedirectUri:
                window.location.origin + '/silent-check-sso.html',
        },
        features: [
            withAutoRefreshToken({
                onInactivityTimeout: 'none',
                sessionTimeout: 240000, // 4 minutes (240 seconds) - refresh before 5min expiry
            }),
        ],
        providers: [
            AutoRefreshTokenService,
            UserActivityService,
            {
                provide: INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG,
                useValue: [urlCondition],
            },
        ],
    });

When I try to build the app I got this error

./apps/coptimo/src/app/core/auth/keycloak.config.ts:11
const backendUrl = import.meta.env.NG_APP_API_URL;
^

TypeError: Cannot read properties of undefined (reading 'NG_APP_API_URL')
at Module.55670 (./apps/coptimo/src/app/core/auth/keycloak.config.ts:11:20)
at webpack_require (./webpack/bootstrap:19:1)
at Module.30379 (./node_modules/rxjs/dist/cjs/internal/scheduler/AsapAction.js:54:32)
at webpack_require (./webpack/bootstrap:19:1)
at Module.92798 (./node_modules/bytes/index.js:170:1)
at webpack_require (./webpack/bootstrap:19:1)

Metadata

Metadata

Assignees

No one assigned

    Labels

    repo requestedReproducing repository is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions