Sub topic 7
Injecting Configuration and Values with InjectionToken
So far, every dependency in this tutorial has been a class. CartService works as its own lookup key: Angular sees the class reference, finds a provider for it, and returns an instance. Many things you want to inject are not classes, though. API base URLs, feature flags, retry limits, a window reference and a plain configuration object all fall into this group. This chapter shows how InjectionToken gives such values a key the injector can use, and how to define, register, default and consume those keys without the usual mistakes.
This chapter assumes you know TypeScript interfaces and generics, standalone components with bootstrapApplication, the inject() function, and the provide/useValue/useFactory provider recipes from the previous chapter.
Why a class or interface cannot be the key
The injector is a runtime map from tokens to providers. A token must therefore exist at runtime. Classes exist at runtime, so they can be tokens. TypeScript interfaces and type aliases do not. The compiler erases them, which leaves nothing for the injector to look up.
export interface AppConfig {
apiUrl: string;
}
// Compile error: 'AppConfig' only refers to a type, but is being used as a value here.
// const config = inject(AppConfig);You could wrap the config in a class just to get a token, but that pushes a runtime class into what is really plain data. A string such as 'apiUrl' is another option you will see in older code. Strings carry no type information, two libraries can pick the same string and collide, and the inject() function does not accept them at all. Its parameter type is ProviderToken<T>, which allows classes, abstract classes and InjectionToken<T>. String tokens only work through the legacy @Inject('apiUrl') constructor decorator.
InjectionToken<T> fills this gap. It is a small object that exists at runtime, so it can serve as a map key, and it carries a type parameter T, so inject() returns a correctly typed value.
| Token kind | Exists at runtime | Typed result from `inject()` | Collision risk | Typical use |
|---|---|---|---|---|
| Class | Yes | Yes, the class type | None | Services |
| Abstract class | Yes | Yes, the abstract type | None | Swappable implementations |
| Interface | No | Not usable | Not applicable | Cannot be a token |
| String | Yes | No, and `inject()` rejects it | High | Legacy code only |
| `InjectionToken<T>` | Yes | Yes, `T` | None, compared by identity | Config, primitives, functions, browser globals |
Defining and providing a token
Creating a token takes one line. The string argument is a description. Angular uses it only in error messages and debugging output, never for matching.
import { InjectionToken, inject } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
export interface AppConfig {
apiUrl: string;
}
export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG');
bootstrapApplication(AppComponent, {
providers: [
{ provide: APP_CONFIG, useValue: { apiUrl: 'https://api.example.com' } }
]
});
// Elsewhere, inside an injection context:
// const config = inject(APP_CONFIG);The useValue object is registered in the application's root environment injector, so any component, directive or service in the app can read it. With useValue, Angular hands back the exact object you supplied. It does not copy or instantiate anything.
In a real project, the token and interface go in their own file (for example app.config.ts) and the bootstrap call stays in main.ts. Consumers then import only the token and never depend on the bootstrap file:
// app.config.ts
import { InjectionToken } from '@angular/core';
export interface AppConfig {
apiUrl: string;
}
export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG');// product.service.ts
import { Injectable, inject } from '@angular/core';
import { APP_CONFIG } from './app.config';
@Injectable({ providedIn: 'root' })
export class ProductService {
private readonly config = inject(APP_CONFIG);
async loadProducts(): Promise<unknown> {
const response = await fetch(`${this.config.apiUrl}/products`);
return response.json();
}
}The type of this.config is inferred as AppConfig from the token's generic parameter. You do not need a type annotation.
How the injector resolves a token
When code calls inject(APP_CONFIG), the injector walks its chain looking for a provider registered under that exact token object. If no injector has one, Angular checks whether the token defines a default factory. If neither exists, it throws.
The order matters. An explicit provider always wins over the token's built-in factory. That rule is what makes defaults overridable, which the next section relies on.
Tree-shakable tokens with a default factory
A token can carry its own provider, in the same way @Injectable({ providedIn: 'root' }) does for a class. You pass an options object with providedIn and a factory:
import { InjectionToken, inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
export const RETRY_LIMIT = new InjectionToken<number>('RETRY_LIMIT', {
providedIn: 'root',
factory: () => 3
});
export const WINDOW = new InjectionToken<Window>('WINDOW', {
providedIn: 'root',
factory: () => {
const view = inject(DOCUMENT).defaultView;
if (!view) {
throw new Error('WINDOW is not available on this platform');
}
return view;
}
});These tokens have three useful properties:
- No registration is needed.
inject(RETRY_LIMIT)returns3even though noprovidersarray mentions it. - They are tree-shakable. If no code imports
RETRY_LIMIT, the token and its factory are dropped from the bundle. - The factory runs in an injection context. That is why
WINDOWcan callinject(DOCUMENT). ReadingDOCUMENTthrough DI instead of the globalwindowkeeps the code working under server-side rendering and makes it easy to fake in tests.
The factory runs once per root injector, and its result is cached. You get a singleton value in the same way you get a singleton service.
An application or test can still override the default:
bootstrapApplication(AppComponent, {
providers: [{ provide: RETRY_LIMIT, useValue: 5 }]
});Packaging tokens in provide functions
Asking every consumer to write { provide: APP_CONFIG, useValue: ... } exposes the token as an implementation detail. Angular's own APIs (provideRouter, provideHttpClient) use a different pattern: a function that returns the providers. You can do the same:
import { EnvironmentProviders, makeEnvironmentProviders } from '@angular/core';
import { APP_CONFIG, AppConfig } from './app.config';
export function provideAppConfig(config: AppConfig): EnvironmentProviders {
return makeEnvironmentProviders([
{ provide: APP_CONFIG, useValue: Object.freeze({ ...config }) }
]);
}bootstrapApplication(AppComponent, {
providers: [provideAppConfig({ apiUrl: 'https://api.example.com' })]
});This brings three benefits. The argument is type-checked against AppConfig where it is written. makeEnvironmentProviders stops the result from being placed in a component's providers array, which is a compile error. Object.freeze stops one consumer from mutating config that every other consumer shares.
Tokens for functions and derived values
Any value can sit behind a token, including functions. A function token is a lightweight way to inject a behavior without defining a service class:
import { InjectionToken } from '@angular/core';
export type Clock = () => Date;
export const CLOCK = new InjectionToken<Clock>('CLOCK', {
providedIn: 'root',
factory: () => () => new Date()
});The double arrow is deliberate. The outer arrow is the factory, and the inner arrow is the Clock it returns. A component then calls inject(CLOCK)() to get the current time. A test provides { provide: CLOCK, useValue: () => new Date('2026-01-01') } and gets a fixed time.
You can also build one token from another with useFactory:
export const PRODUCTS_URL = new InjectionToken<string>('PRODUCTS_URL');
export const productUrlProvider = {
provide: PRODUCTS_URL,
useFactory: () => `${inject(APP_CONFIG).apiUrl}/products`
};Common errors and edge cases
NullInjectorError at runtime. The token has no provider and no default factory. Check that the provider sits in bootstrapApplication or in a route's providers, and not only in a test or in an unrelated lazy route.
Two tokens with the same description. Tokens are compared by object identity, not by description. This code creates two unrelated tokens:
const A = new InjectionToken<string>('API_URL');
const B = new InjectionToken<string>('API_URL');
// Providing A does nothing for inject(B).In practice this happens when a token is defined inside a function that runs more than once, or when a library ends up bundled twice under different paths. Define each token once, at module top level, and export it.
Type mismatch is not checked at the provider. { provide: RETRY_LIMIT, useValue: '5' } compiles because a provider literal is not tied to the token's generic. The consumer then receives a string typed as number. A provideX() function with a typed parameter closes this gap.
Shared mutable objects. A useValue object is shared by reference, so a component that runs config.apiUrl = '...' changes it for the whole app. Freeze the object or declare its fields readonly.
Overriding in a subtree. Because tokens resolve through the injector hierarchy like classes do, a component or route can provide its own value for APP_CONFIG, and its descendants see that value instead. The hierarchy chapters cover the exact lookup rules.
One token, many values. By default, a later provider for the same token replaces an earlier one. Collecting several values under one token, such as a list of validators or interceptors, needs multi: true, which has its own chapter.
Exercise
A teammate writes export const FEATURE_FLAGS = new InjectionToken<Record<string, boolean>>('FEATURE_FLAGS'); and calls inject(FEATURE_FLAGS) in a service, but never adds a provider. What happens, and how would you change the token so the service gets an empty set of flags unless the app supplies some, while still allowing the app to override it?
Show answer
The call throws NullInjectorError ("No provider for InjectionToken FEATUREFLAGS") because no injector has a provider and the token has no default factory. Give the token a default: `new InjectionToken<Record<string, boolean>>('FEATUREFLAGS', { providedIn: 'root', factory: () => ({}) }). The app can still override it with { provide: FEATURE_FLAGS, useValue: { beta: true } }` at bootstrap, because explicit providers take precedence over the token's factory.
Exercise
Two files each contain export const API_URL = new InjectionToken<string>('API_URL');. main.ts provides the token imported from config-a.ts, and a service injects the one imported from config-b.ts. Does the service receive the URL? Explain why.
Show answer
No. The service gets NullInjectorError (or the token's default, if it has one). InjectionToken instances are matched by object identity. The description string is only a label for error messages, so these are two distinct tokens. Fix it by defining the token once and importing that single constant everywhere.
Exercise
Write a tree-shakable token CLOCK of type () => Date whose default returns the current time, and show the provider a test would use to freeze time at 2026-01-01.
Show answer
export const CLOCK = new InjectionToken<() => Date>('CLOCK', { providedIn: 'root', factory: () => () => new Date() }); In the test: providers: [{ provide: CLOCK, useValue: () => new Date('2026-01-01') }]. The outer arrow in the factory is the factory itself, and the inner arrow is the clock function it returns.