Sub topic 4
What belongs in core and shared
This chapter assumes you know TypeScript, standalone components, dependency injection, and how to configure the Angular Router. The previous chapter showed how to lay out feature folders. Here you decide where the code that is not a feature goes. In most apps this code is a small part of the codebase. It still causes most of the dependency problems.
Two folders, two different jobs
Most apps need a place for code that several features use. Two folders usually appear, and they are different things.
- core holds app-wide singletons and wiring. The app creates each of these once and keeps it alive for the whole session. Examples are the authentication service, HTTP interceptors, the app shell (header, navigation, footer), and configuration tokens.
- shared holds reusable building blocks that carry no app state. Examples are presentational components, pipes, directives, and small utility functions. A feature can use them as many times as it wants, and each use is independent.
The test is lifetime and state. If removing a second copy of the code would break the app, it is core. If every user of the code simply gets their own instance, it is shared.
src/app/
app.component.ts
app.config.ts
app.routes.ts
core/
auth/
auth.service.ts
auth.interceptor.ts
layout/
shell.component.ts
config/
api-url.token.ts
shared/
ui/
status-badge.component.ts
pipes/
truncate.pipe.ts
util/
date-helpers.ts
orders/
customers/How the dependencies flow
Features may use core and shared. Core and shared must not use features. If a shared button imports an OrdersStore, the "shared" folder is no longer shared. It now depends on one feature, and every feature that uses the button pulls that feature in too.
Features do not import each other directly. The chapter on cross-feature communication covers that case.
The diagram allows core to import from shared, for example when the shell uses a shared icon component. The reverse is not allowed. Shared code must stay free of app-wide state, so it should never need core.
What goes in core
Core is where you put things that must exist exactly once. In a standalone app there is no CoreModule. Core code is registered in app.config.ts and provided at the root.
A typical core service uses providedIn: 'root', which makes Angular create one instance in the root injector:
// src/app/core/auth/auth.service.ts
import { Injectable, computed, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly _token = signal<string | null>(null);
readonly token = this._token.asReadonly();
readonly isLoggedIn = computed(() => this._token() !== null);
signIn(token: string): void {
this._token.set(token);
}
signOut(): void {
this._token.set(null);
}
}A functional interceptor reads the token and adds it to outgoing requests. It lives in core because it affects every HTTP call in the app:
// src/app/core/auth/auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).token();
if (!token) {
return next(req);
}
return next(
req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }),
);
};The application config is the single place where core pieces are wired up:
// src/app/app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { routes } from './app.routes';
import { authInterceptor } from './core/auth/auth.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withInterceptors([authInterceptor])),
],
};Good candidates for core:
- Authentication state and route guards that every feature relies on.
- HTTP interceptors for auth, error reporting, and correlation IDs.
- The app shell component and top-level layout.
- Injection tokens for runtime configuration, such as an API base URL.
- Global error handling and logging services.
Providing core without a module
Older apps wrapped this in a CoreModule and guarded it against being imported twice. Standalone apps don't need that guard. providedIn: 'root' and ApplicationConfig already guarantee one instance, because only the bootstrap call sets up the root injector.
If a core piece needs setup, expose a provideXxx() function next to it, as Angular does with provideHttpClient(). This keeps app.config.ts short and keeps each core area in charge of its own wiring.
What goes in shared
Shared code is reusable and has no knowledge of any feature. It receives data through inputs and reports user actions through outputs. It does not fetch data and does not inject app-wide stores.
// src/app/shared/ui/status-badge.component.ts
import { Component, input } from '@angular/core';
@Component({
selector: 'app-status-badge',
standalone: true,
template: `<span class="badge" [class]="'badge-' + tone()">{{ label() }}</span>`,
})
export class StatusBadgeComponent {
readonly label = input.required<string>();
readonly tone = input<'info' | 'success' | 'danger'>('info');
}Pipes follow the same rule. They are pure functions of their input:
// src/app/shared/pipes/truncate.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'truncate', standalone: true })
export class TruncatePipe implements PipeTransform {
transform(value: string, max = 40): string {
return value.length > max ? value.slice(0, max - 1) + '…' : value;
}
}A feature component imports exactly what it uses:
import { Component } from '@angular/core';
import { StatusBadgeComponent } from '../../shared/ui/status-badge.component';
import { TruncatePipe } from '../../shared/pipes/truncate.pipe';
@Component({
selector: 'app-order-row',
standalone: true,
imports: [StatusBadgeComponent, TruncatePipe],
template: `
<p>{{ note | truncate: 30 }}</p>
<app-status-badge label="Shipped" tone="success" />
`,
})
export class OrderRowComponent {
note = 'Customer asked for delivery after 5 pm on weekdays only.';
}Because each standalone piece is imported directly, the compiler can remove unused ones. This is why you do not need one big SharedModule that re-exports everything.
Keeping the two folders honest
Shared and core attract code that has no better home. Over time they turn into dumping grounds. Four checks help you decide before you add a file.
- Does exactly one feature use it? Keep it in that feature. Moving it to shared "in case" creates a dependency you will have to maintain.
- Does it know about a business concept? A
OrderStatusBadgeknows about orders, so it belongs to the orders feature. AStatusBadgethat takes a label and a tone is shared. - Does it hold state or call the server? Then it is not shared. Place it in core if it is app-wide, or in a feature if it is not.
- Is it used by two or more features, and would a change to it affect both? Then promote it to shared. Wait for the second real user rather than guessing.
| Code | Where it goes | Reason |
|---|---|---|
| Auth token storage | core | One instance for the whole app |
| Currency pipe wrapper | shared | Pure, no state, many users |
| Order list filter logic | orders feature | Business rule for one feature |
| Generic data table component | shared | Inputs and outputs only |
| Table that loads customers | customers feature | It fetches feature data |
| Global error notification service | core | App-wide singleton |
Common mistakes
- Shared importing from a feature. A shared component imports a model type from
orders/. Move the type to shared if it is truly generic, or move the component into the feature. - Providing stateful services in shared. A shared service with
providedIn: 'root'is a core service in disguise. Every feature then shares one instance, which is rarely intended. - Core growing a
utilsfolder. Utilities with no state belong in shared. Core should contain things that are created and wired once. - Putting feature routes in core. Feature routes are part of the feature. The app-level routes file only maps URL prefixes to lazy features.
- Reaching into the core folder from library-style shared code. If you plan to move shared into its own library later, any import from core will block that move.
These rules are easy to state and easy to break by accident, so later chapters turn them into lint rules that fail the build.
Exercise
Your team has OrderStatusBadgeComponent in shared/ui. It injects OrdersStore to look up a status color. Two problems follow from that. Name them and say where the component should live or how to change it.
Show answer
First, shared now depends on the orders feature, which breaks the rule that shared must not import features, and every feature using the badge pulls in orders code. Second, the component holds knowledge of a business concept, so it is no longer generic. Either move it into the orders feature, or turn it into a generic StatusBadgeComponent with label and tone inputs and let the orders feature compute the tone from its store and pass it in.
Exercise
A new NotificationService shows toast messages. Several features call it, it keeps a list of current toasts as a signal, and the shell renders that list. Should it go in core or shared, and which providedIn value fits?
Show answer
Core, with providedIn: 'root'. It holds app-wide state that the shell and many features must see as one instance, which matches the core definition. The toast display component that only takes a message and a tone as inputs can still be a shared UI component.