medium.com 10 min read Original Source

Stop Importing Angular environment Directly Into Every Feature

Environment configuration is infrastructure. Your Orders, Payments, and Customer features should not know how deployment configuration is stored.

Most Angular applications begin with something familiar:

export const environment = {
  production: false,
  apiUrl: 'https://dev-api.example.com',
  enablePaymentsV2: true
};
export const environment = {
  production: false,
  apiUrl: 'https://dev-api.example.com',
  enablePaymentsV2: true
};

Then a service needs the API URL:

import { environment }
  from '../../environments/environment';

@Injectable()
export class OrderService {
  private readonly apiUrl =
    environment.apiUrl;
  ...
}
import { environment }
  from '../../environments/environment';

@Injectable()
export class OrderService {
  private readonly apiUrl =
    environment.apiUrl;
  ...
}

Perfectly reasonable.

Then another feature imports it.

And another.

Eventually:

Orders
Payments
Customers
Reports
Dashboard
Authentication
Orders
Payments
Customers
Reports
Dashboard
Authentication

all import:

environment
environment

directly.

Soon features contain logic like:

if (
  environment.production
) {
  ...
}
if (
  environment.production
) {
  ...
}

or:

if (
  environment.region === 'EU'
) {
  ...
}
if (
  environment.region === 'EU'
) {
  ...
}

or:

if (
  environment.enableRefundV2
) {
  ...
}
if (
  environment.enableRefundV2
) {
  ...
}

Now your deployment configuration is no longer an infrastructure detail.

It has become part of your feature architecture.

That coupling is easy to create and surprisingly expensive to remove.

environment.ts Is Convenient — Maybe Too Convenient

Angular environment files solve a useful problem.

You can provide different build-time values for:

development
test
production
development
test
production

For example:

export const environment = {
  production: true,
  apiBaseUrl:
    'https://api.example.com'
};
export const environment = {
  production: true,
  apiBaseUrl:
    'https://api.example.com'
};

The problem begins when every feature reads these values directly.

Consider:

@Injectable()
export class PaymentRepository {
  private readonly endpoint =
    `${environment.apiBaseUrl}/payments`;
}
@Injectable()
export class PaymentRepository {
  private readonly endpoint =
    `${environment.apiBaseUrl}/payments`;
}

Now the Payment feature knows:

where deployment configuration lives
where deployment configuration lives

instead of simply knowing:

which Payments API it should call
which Payments API it should call

Those are different responsibilities.

Features Should Depend on Configuration Meaning

Imagine Payments needs:

Payments API URL
Payments API URL

Instead of:

environment.apiBaseUrl
environment.apiBaseUrl

the feature should ideally depend on something like:

PAYMENTS_API_URL
PAYMENTS_API_URL

or:

PaymentConfig
PaymentConfig

The feature asks for what it needs.

It does not ask:

“Which environment am I currently running in?”

That distinction creates a much cleaner boundary.

The Problem With environment.production

This is especially common:

if (
  environment.production
) {
  enableTelemetry();
}
if (
  environment.production
) {
  enableTelemetry();
}

or:

if (
  !environment.production
) {
  showDebugPanel();
}
if (
  !environment.production
) {
  showDebugPanel();
}

Now behavior depends on an extremely broad concept:

production
production

But what does production actually mean?

Maybe telemetry should also run in:

UAT
Staging
Performance
UAT
Staging
Performance

Maybe the debug panel should be disabled in:

shared QA environments
shared QA environments

A feature usually does not care whether the application is technically “production.”

It cares about a specific capability.

Prefer:

telemetryEnabled
telemetryEnabled

over:

production
production

Specific configuration creates better semantics.

Environment Name Should Not Become Business Logic

This is worse:

if (
  environment.name === 'prod'
) {
  useNewSettlementLogic();
}
if (
  environment.name === 'prod'
) {
  useNewSettlementLogic();
}

Now deployment topology determines business behavior.

Imagine tomorrow you add:

DR Production
DR Production

or:

Pre-Production
Pre-Production

Should the logic run there?

Nobody knows.

The condition is really hiding some other meaning.

Perhaps:

settlementV2Enabled
settlementV2Enabled

or:

settlementMode
settlementMode

should be explicit.

Do not make environment names act like feature flags or business rules.

Build-Time Configuration Has Limitations

Angular environment replacement traditionally happens during the build.

Conceptually:

DEV build
→ DEV configuration

PROD build
→ PROD configuration
DEV build
→ DEV configuration

PROD build
→ PROD configuration

That works well when every environment gets its own build.

But many enterprise teams want:

Build once
Deploy many
Build once
Deploy many

For example:

Same artifact
   ↓
DEV
UAT
PROD
Same artifact
   ↓
DEV
UAT
PROD

Now build-time environment files become restrictive.

If configuration is compiled into the JavaScript bundle:

API URL
Tenant settings
Operational switches
API URL
Tenant settings
Operational switches

changing configuration may require another build.

That may not match your deployment model.

Runtime Configuration Solves a Different Problem

A runtime configuration could look like:

{
  "apiBaseUrl":
    "https://api.example.com",

"telemetryEnabled":
    true,
  "supportUrl":
    "https://support.example.com"
}
{
  "apiBaseUrl":
    "https://api.example.com",

"telemetryEnabled":
    true,
  "supportUrl":
    "https://support.example.com"
}

The deployed application loads it when starting.

Conceptually:

Angular bundle
     +
Runtime config
     ↓
Deployment
Angular bundle
     +
Runtime config
     ↓
Deployment

Now the same application artifact can operate in multiple environments.

But runtime configuration introduces another architectural question:

How should features consume it?

The answer should usually not be:

configService.config().anything
configService.config().anything

everywhere.

Avoid a Giant Global Configuration Object

A common runtime service:

<button data-code="@Injectable({
providedIn: 'root'
})
export class AppConfigService {
readonly config =
signal(
null
);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

@Injectable({
  providedIn: 'root'
})
export class AppConfigService {
  readonly config =
    signal<AppConfig | null>(
      null
    );
}
@Injectable({
  providedIn: 'root'
})
export class AppConfigService {
  readonly config =
    signal<AppConfig | null>(
      null
    );
}

Then features do:

this.config
  .config()!
  .payments
  .refund
  .enabled;
this.config
  .config()!
  .payments
  .refund
  .enabled;

Or:

this.config
  .config()!
  .services
  .orderApi
  .url;
this.config
  .config()!
  .services
  .orderApi
  .url;

This is better than importing environment files directly in some ways.

But every feature still understands the entire global configuration structure.

You moved the coupling.

You did not remove it.

Give Features Narrow Configuration Contracts

Suppose Orders needs:

API base URL
Maximum export size
API base URL
Maximum export size

Create an explicit contract:

export interface OrderFeatureConfig {
  apiUrl: string;
  maxExportRows: number;
}
export interface OrderFeatureConfig {
  apiUrl: string;
  maxExportRows: number;
}

Then provide it through DI.

<button data-code="export const ORDER_FEATURE_CONFIG =
new InjectionToken(
'ORDER_FEATURE_CONFIG'
);” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

export const ORDER_FEATURE_CONFIG =
  new InjectionToken<OrderFeatureConfig>(
    'ORDER_FEATURE_CONFIG'
  );
export const ORDER_FEATURE_CONFIG =
  new InjectionToken<OrderFeatureConfig>(
    'ORDER_FEATURE_CONFIG'
  );

Repository:

<button data-code="@Injectable()
export class OrderRepository {
private readonly config =
inject(
ORDER_FEATURE_CONFIG
);

private readonly http =
inject(HttpClient);
getOrders() {
return this.http.get(
`${this.config.apiUrl}/orders`
);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

@Injectable()
export class OrderRepository {
  private readonly config =
    inject(
      ORDER_FEATURE_CONFIG
    );

private readonly http =
    inject(HttpClient);
  getOrders() {
    return this.http.get<OrderDto[]>(
      `${this.config.apiUrl}/orders`
    );
  }
}
@Injectable()
export class OrderRepository {
  private readonly config =
    inject(
      ORDER_FEATURE_CONFIG
    );

private readonly http =
    inject(HttpClient);
  getOrders() {
    return this.http.get<OrderDto[]>(
      `${this.config.apiUrl}/orders`
    );
  }
}

Orders now depends on:

OrderFeatureConfig
OrderFeatureConfig

not:

environment.ts
environment.ts

and not:

the complete application configuration schema
the complete application configuration schema

The Composition Root Connects Configuration

At application setup:

const runtimeConfig =
  inject(RuntimeConfig);

return [
  {
    provide:
      ORDER_FEATURE_CONFIG,
    useValue: {
      apiUrl:
        runtimeConfig.orderApiUrl,
      maxExportRows:
        runtimeConfig
          .orderMaxExportRows
    }
  }
];
const runtimeConfig =
  inject(RuntimeConfig);

return [
  {
    provide:
      ORDER_FEATURE_CONFIG,
    useValue: {
      apiUrl:
        runtimeConfig.orderApiUrl,
      maxExportRows:
        runtimeConfig
          .orderMaxExportRows
    }
  }
];

Conceptually:

Deployment Config
       ↓
Application Composition
       ↓
OrderFeatureConfig
       ↓
Orders
Deployment Config
       ↓
Application Composition
       ↓
OrderFeatureConfig
       ↓
Orders

That dependency direction is much healthier.

The Feature Should Not Know Where the Value Came From

Orders should not care whether:

apiUrl
apiUrl

came from:

environment.ts
environment.ts

or:

runtime-config.json
runtime-config.json

or:

server-rendered configuration
server-rendered configuration

or:

an injection token
an injection token

Its contract is simply:

interface OrderFeatureConfig {
  apiUrl: string;
}
interface OrderFeatureConfig {
  apiUrl: string;
}

That independence makes deployment architecture easier to change.

Configuration and Feature Flags Are Not the Same Thing

Consider:

enableRefundV2: true
enableRefundV2: true

Is that:

runtime configuration?
runtime configuration?

or:

feature flag?
feature flag?

If the value exists to control gradual rollout:

10% → 50% → 100%
10% → 50% → 100%

it is probably a feature flag.

If the value represents stable deployment configuration:

Payment provider for region
Payment provider for region

it may be configuration.

If it represents:

Can this customer perform refunds?
Can this customer perform refunds?

it may be authorization or business policy.

Do not create one configuration object that becomes the owner of every boolean in the application.

Configuration and Business Rules Are Different

Suppose:

environment.maxRefundAmount =
  5000;
environment.maxRefundAmount =
  5000;

Then:

environment.maxRefundAmount
) {
…
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

if (
  refund.amount >
    environment.maxRefundAmount
) {
  ...
}
if (
  refund.amount >
    environment.maxRefundAmount
) {
  ...
}

Now an environment file contains business behavior.

Maybe the refund limit really is externally configurable.

That can be valid.

But then name and own it accordingly.

Perhaps:

RefundPolicyConfig
RefundPolicyConfig

belongs to the Payments capability.

Do not treat business policy as generic deployment configuration merely because the value is configurable.

Configuration Should Usually Be Typed

Avoid:

config.get(
  'order-api-url'
);
config.get(
  'order-api-url'
);

returning:

any
any

or:

string | undefined
string | undefined

throughout the application.

Prefer:

interface RuntimeConfig {
  orderApiUrl: string;
  paymentApiUrl: string;
  telemetryEnabled: boolean;
}
interface RuntimeConfig {
  orderApiUrl: string;
  paymentApiUrl: string;
  telemetryEnabled: boolean;
}

Then validate the configuration at the boundary.

The rest of the application consumes known values.

Runtime Config Is External Input Too

A JSON file can be malformed.

For example:

{
  "orderApiUrl": null,
  "telemetryEnabled": "yes"
}
{
  "orderApiUrl": null,
  "telemetryEnabled": "yes"
}

TypeScript does not protect you at runtime.

You can validate once:

const RuntimeConfigSchema =
  z.object({
    orderApiUrl:
      z.string().url(),

paymentApiUrl:
      z.string().url(),
    telemetryEnabled:
      z.boolean()
  });
const RuntimeConfigSchema =
  z.object({
    orderApiUrl:
      z.string().url(),

paymentApiUrl:
      z.string().url(),
    telemetryEnabled:
      z.boolean()
  });

Then:

const config =
  RuntimeConfigSchema.parse(
    response
  );
const config =
  RuntimeConfigSchema.parse(
    response
  );

Now invalid deployment configuration fails at a clear boundary.

Fail Early for Critical Configuration

Suppose:

Order API URL
Order API URL

is missing.

Allowing Angular to continue may produce:

404
404
404
404
404
404

across unrelated requests.

It may be better for startup validation to fail with something explicit:

Invalid runtime configuration:
orderApiUrl is missing.
Invalid runtime configuration:
orderApiUrl is missing.

Critical platform configuration is one of the legitimate reasons to validate during startup.

But after configuration is loaded, keep its usage narrow.

Do Not Let Components Build API URLs

Avoid:

export class OrderPage {
  private readonly api =
    environment.apiBaseUrl;

download(orderId: string) {
    window.open(
      `${this.api}/orders/${orderId}/document`
    );
  }
}
export class OrderPage {
  private readonly api =
    environment.apiBaseUrl;

download(orderId: string) {
    window.open(
      `${this.api}/orders/${orderId}/document`
    );
  }
}

The component now understands infrastructure.

Prefer an application capability:

documents.downloadOrderDocument(
  orderId
);
documents.downloadOrderDocument(
  orderId
);

or a repository returning the appropriate URL.

Components should focus on interaction and presentation.

Do Not Scatter Region Checks Either

Enterprise applications often end up with:

if (
  environment.region === 'APAC'
) {
  ...
}
if (
  environment.region === 'APAC'
) {
  ...
}

in multiple components.

Then:

if (
  environment.region === 'EMEA'
) {
  ...
}
if (
  environment.region === 'EMEA'
) {
  ...
}

elsewhere.

What does Region actually control?

Perhaps:

Date formatting
Payment provider
Available products
Legal workflow
Date formatting
Payment provider
Available products
Legal workflow

Those have different owners.

A global region string should not become a shortcut for several unrelated decisions.

Translate Configuration Into Capabilities

Suppose a deployment supports document export.

Instead of components reading:

config.exportEnabled
config.exportEnabled

you may expose:

this.featureConfig
.exportEnabled
);” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

readonly canExport =
  computed(() =>
    this.featureConfig
      .exportEnabled
  );
readonly canExport =
  computed(() =>
    this.featureConfig
      .exportEnabled
  );

Or combine configuration with other policy:

this.featureConfig
.exportEnabled &&
this.authorization
.canExport() &&
this.orders().length > 0
);” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

readonly canExport =
  computed(() =>
    this.featureConfig
      .exportEnabled &&
    this.authorization
      .canExport() &&
    this.orders().length > 0
  );
readonly canExport =
  computed(() =>
    this.featureConfig
      .exportEnabled &&
    this.authorization
      .canExport() &&
    this.orders().length > 0
  );

Now the UI consumes:

canExport
canExport

not infrastructure configuration.

Be Careful Not to Wrap Every Config Value

This can go too far.

If a repository simply needs:

apiUrl
apiUrl

there is no need to create:

OrderApiUrlProviderService
OrderApiUrlProviderService

around a single InjectionToken.

Likewise, do not create five layers between:

config
config

and:

HTTP request
HTTP request

without a reason.

The simplest boundary may be:

<button data-code="InjectionToken” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

InjectionToken<OrderFeatureConfig>
InjectionToken<OrderFeatureConfig>

That is enough.

Feature Libraries Benefit Even More

Imagine you build:

libs/orders/
libs/orders/

for reuse across several applications.

If the library imports:

../../../environments/environment
../../../environments/environment

it is no longer truly reusable.

The library assumes:

  • one application structure
  • one environment implementation
  • one deployment model

Instead, expose configuration:

provideOrders({
  apiUrl: ...
});
provideOrders({
  apiUrl: ...
});

The application supplies the value.

The library owns the behavior.

Provider Functions Make This Clean

For example:

export function provideOrders(
  config: OrderFeatureConfig
): EnvironmentProviders {
  return makeEnvironmentProviders([
    {
      provide:
        ORDER_FEATURE_CONFIG,

useValue:
        config
    },
    OrderRepository,
    OrderStore
  ]);
}
export function provideOrders(
  config: OrderFeatureConfig
): EnvironmentProviders {
  return makeEnvironmentProviders([
    {
      provide:
        ORDER_FEATURE_CONFIG,

useValue:
        config
    },
    OrderRepository,
    OrderStore
  ]);
}

Then application setup:

providers: [
  provideOrders({
    apiUrl:
      runtimeConfig.orderApiUrl,

maxExportRows:
      10000
  })
]
providers: [
  provideOrders({
    apiUrl:
      runtimeConfig.orderApiUrl,

maxExportRows:
      10000
  })
]

Now the feature has an explicit configuration boundary.

Route Providers Can Configure Feature Instances Too

Maybe different routes need different behavior.

{
  path: 'archived-orders',

providers: [
    {
      provide:
        ORDER_FEATURE_CONFIG,
      useValue: {
        mode: 'archive',
        pageSize: 100
      }
    }
  ]
}
{
  path: 'archived-orders',

providers: [
    {
      provide:
        ORDER_FEATURE_CONFIG,
      useValue: {
        mode: 'archive',
        pageSize: 100
      }
    }
  ]
}

Now configuration can follow provider scope.

That is much more flexible than globally reading:

environment.orderMode
environment.orderMode

inside the feature.

Not Every Configuration Value Is Global

This is a subtle but important point.

Teams often assume:

configuration
=
application singleton
configuration
=
application singleton

But configuration can have scopes.

For example:

Application config
→ API URLs

Tenant config
→ enabled business capabilities

Feature config
→ feature defaults

Route config
→ screen-specific behavior
Application config
→ API URLs

Tenant config
→ enabled business capabilities

Feature config
→ feature defaults

Route config
→ screen-specific behavior

One giant global config service may flatten all of these lifetimes.

Tenant Configuration Deserves Tenant Lifetime

Suppose:

Tenant A
→ max export 5,000

Tenant B
→ max export 20,000
Tenant A
→ max export 5,000

Tenant B
→ max export 20,000

That is not static application configuration.

It changes when:

tenant changes
tenant changes

A root immutable environment file cannot model that correctly.

You need tenant-owned configuration.

Conceptually:

Application Config
       ↓
Session/Tenant Context
       ↓
Tenant Capabilities
       ↓
Feature
Application Config
       ↓
Session/Tenant Context
       ↓
Tenant Capabilities
       ↓
Feature

Again, ownership matters.

User Preferences Are Not Environment Configuration

Likewise:

default page size = 50
default page size = 50

might actually be a user preference.

Do not put everything adjustable into:

AppConfig
AppConfig

just because it is configurable.

Ask:

Who owns the value?

Who can change it?

How long should it live?
Who owns the value?

Who can change it?

How long should it live?

Those answers determine where it belongs.

Configuration Should Not Be a Secret Store

Another trap:

config.set(
  'currentCustomer',
  customer
);
config.set(
  'currentCustomer',
  customer
);

or:

config.set(
  'selectedRegion',
  region
);
config.set(
  'selectedRegion',
  region
);

Now configuration service is becoming generic application state.

Configuration should describe how the application/feature is configured.

It should not become another random state container.

Environment Variables Are Not Automatically Secure

This matters in frontend applications.

Anything compiled into or delivered to the browser can generally be inspected by the user.

Do not put:

Database password
Private API key
Service account secret
Database password
Private API key
Service account secret

inside Angular environment files.

Frontend configuration is client-visible.

Use the backend for secret-bearing integrations.

Angular can hold public identifiers and client configuration.

Not server secrets.

API Keys Need Context

Some browser-facing services intentionally use public client keys.

For example:

Maps public browser key
Analytics measurement ID
Maps public browser key
Analytics measurement ID

Those may legitimately exist in frontend configuration.

But treat them as public credentials with appropriate provider restrictions.

Do not assume the word:

environment
environment

makes a value secret.

It does not.

Testing Improves With Explicit Configuration

Direct environment import:

import {
  environment
} from '../environments/environment';
import {
  environment
} from '../environments/environment';

creates a static dependency.

Tests may need awkward module mocking or build-specific setup.

With DI:

TestBed.configureTestingModule({
  providers: [
    {
      provide:
        ORDER_FEATURE_CONFIG,

useValue: {
        apiUrl:
          '/test-api',
        maxExportRows:
          100
      }
    }
  ]
});
TestBed.configureTestingModule({
  providers: [
    {
      provide:
        ORDER_FEATURE_CONFIG,

useValue: {
        apiUrl:
          '/test-api',
        maxExportRows:
          100
      }
    }
  ]
});

Now the test controls configuration explicitly.

No production environment leakage.

Test Different Configurations Easily

For example:

{
provideConfig({
maxExportRows:
100
});

…
}
);” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

it(
  'blocks export above configured limit',
  () => {
    provideConfig({
      maxExportRows:
        100
    });

...
  }
);
it(
  'blocks export above configured limit',
  () => {
    provideConfig({
      maxExportRows:
        100
    });

...
  }
);

Another:

{
provideConfig({
maxExportRows:
10000
});

…
}
);” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

it(
  'allows larger exports when configured',
  () => {
    provideConfig({
      maxExportRows:
        10000
    });

...
  }
);
it(
  'allows larger exports when configured',
  () => {
    provideConfig({
      maxExportRows:
        10000
    });

...
  }
);

Configuration becomes a testable dependency.

Not a hidden module import.

Explicit Configuration Documents Dependencies

This constructor:

private readonly config =
  inject(
    ORDER_FEATURE_CONFIG
  );
private readonly config =
  inject(
    ORDER_FEATURE_CONFIG
  );

tells a developer:

Orders depends on Orders configuration.

This:

environment.someValue
environment.someValue

hidden halfway through a method does not make that dependency obvious.

Good dependency injection makes architecture visible.

Avoid Generic getConfig("some.string.path")

It looks flexible:

config.get(
  'features.orders.export.limit'
);
config.get(
  'features.orders.export.limit'
);

But now:

  • strings are not type-safe
  • refactoring is harder
  • feature dependencies are implicit
  • global config structure leaks everywhere

Prefer strongly typed contracts.

interface OrderFeatureConfig {
  exportLimit: number;
}
interface OrderFeatureConfig {
  exportLimit: number;
}

The feature should know its contract.

Not the entire configuration tree.

Warning Signs

Your Angular configuration architecture may need attention when:

  • many features import environment directly
  • components check environment.production
  • business behavior depends on environment names
  • one global config object is accessed throughout the application
  • features know deeply nested runtime-config paths
  • reusable libraries import application environment files
  • changing an API URL requires touching feature code
  • configuration values use untyped string keys
  • tenant configuration is mixed with deployment configuration
  • user preferences are stored in global app config
  • secrets are included in frontend environment files
  • tests need to mock static environment imports

Several of these together usually mean deployment details are leaking into feature architecture.

A Practical Decision Framework

Before adding another value to environment.ts, ask:

1. Who owns this value?

Application platform?

Tenant?

Feature?

User?

Business policy?

2. Does the feature need the value or only its meaning?

Prefer meaningful capabilities where appropriate.

3. Does the value need to change without rebuilding?

If yes, consider runtime configuration.

4. Does every feature really need access?

Expose narrow typed contracts.

5. Is this actually a feature flag or business rule?

Do not hide unrelated concerns inside configuration.

6. Is the value sensitive?

If it must remain secret, it does not belong in the Angular client.

A Cleaner Architecture

Instead of:

            environment.ts
                   │
       ┌───────────┼───────────┐
       ▼           ▼           ▼
     Orders     Payments    Customers
       │           │           │
       └── production? ────────┘
             region?
             flags?
             URLs?
            environment.ts
                   │
       ┌───────────┼───────────┐
       ▼           ▼           ▼
     Orders     Payments    Customers
       │           │           │
       └── production? ────────┘
             region?
             flags?
             URLs?

prefer:

          Deployment / Runtime Config
                    │
                    ▼
           Application Composition
           /          |          
          ▼           ▼           ▼
   Order Config  Payment Config  Platform Config
          │           │
          ▼           ▼
       Orders      Payments
          Deployment / Runtime Config
                    │
                    ▼
           Application Composition
           /          |          
          ▼           ▼           ▼
   Order Config  Payment Config  Platform Config
          │           │
          ▼           ▼
       Orders      Payments

And separately:

Feature Flags
→ rollout

Authorization
→ user permissions

Tenant Context
→ tenant capabilities

Business Policy
→ domain rules
Feature Flags
→ rollout

Authorization
→ user permissions

Tenant Context
→ tenant capabilities

Business Policy
→ domain rules

Each concern has a clear owner.

Final Thoughts

Angular environment files are useful.

There is nothing inherently wrong with them.

The problem appears when:

environment
environment

becomes a globally imported dependency that every feature uses to answer unrelated questions.

Features should not care whether configuration came from:

environment.ts
runtime JSON
deployment variables
server-generated config
environment.ts
runtime JSON
deployment variables
server-generated config

They should depend on the smallest meaningful configuration contract they need.

That makes features:

  • easier to test
  • easier to reuse
  • easier to deploy
  • less coupled to infrastructure
  • more explicit about their dependencies

You do not need an elaborate configuration framework.

Often an InjectionToken and a typed interface are enough.

The goal is not maximum abstraction.

The goal is preventing deployment mechanics from becoming business architecture.

Key Takeaway

environment.ts is a configuration mechanism — not your application’s global dependency API.

Avoid importing it throughout feature code.

Expose narrow typed configuration contracts.

Use runtime configuration when values must change independently of the build.

Keep feature flags, tenant capabilities, business rules, and user preferences separate.

Do not place secrets in client-side Angular configuration.

And use dependency injection to make configuration dependencies visible.

Your features should know what they need — not how your deployment stores it.

Stop Turning One Angular Feature Store Into the State Owner for Every Screen
A feature store should own cohesive state — not become a permanent container for every page, dialog, filter, workflow…

Connect with Me

If you enjoyed this post and would like to stay updated with more content like this, feel free to connect with me on social media:

Email: Email me on [email protected] for any questions, collaborations, or just to say hi!

I appreciate your support and look forward to connecting with you!