Skip to content

API Reference Controller

Taras Demyanets edited this page Mar 31, 2026 · 1 revision

API Reference: Controller

Package: @microfrontend/controller Version: 1.10.0 Install: npm install @microfrontend/controller Peer dependency: @microfrontend/common ^1.6.0

This package is installed in the shell application.


MetaRouter

The central class that manages microfrontend routing, iframe lifecycle, and inter-app messaging.

import { MetaRouter } from '@microfrontend/controller';

Constructor

constructor(config: MetaRouterConfig)
Parameter Type Description
config MetaRouterConfig Configuration for the meta router

Creates a new MetaRouter instance. On construction, it:

  • Sets up a hashchange listener on the window
  • Creates a MessagingApiBroker to handle incoming postMessage events
  • Initializes the FramesManager for iframe management

Methods

initialize(): Promise<void>

Initializes the meta router. If the current URL has a hash, it routes to the encoded state. Otherwise, it navigates to the first configured route.

await router.initialize();

Note: Call preload() before initialize() if you want iframes to be pre-created.

preload(routesToPreload?: IAppConfig[]): Promise<IFrameFacade[]>

Creates iframes for routes and appends them (hidden) to the outlet element. If no routesToPreload is specified, all configured routes are preloaded.

// Preload all routes
await router.preload();

// Preload specific routes
await router.preload([routes[0]]);

go(metaRoute: string, subRoute?: string): Promise<void>

Navigates to a microfrontend. Shows the target iframe, hides all others, updates the URL hash, and notifies the microfrontend.

// Navigate to microfrontend 'dashboard'
await router.go('dashboard');

// Navigate to microfrontend 'dashboard' with subroute 'users'
await router.go('dashboard', 'users');

If the current microfrontend has unsaved state and a allowStateDiscardCallback is registered, the callback is invoked first. Navigation is rejected if the callback returns false.

broadcast(tag: string, data: object, recipients?: string[]): Promise<void>

Sends a broadcast message to microfrontends. If recipients is omitted, the message is sent to all loaded microfrontends.

// Broadcast to all microfrontends
router.broadcast('theme-changed', { theme: 'dark' });

// Broadcast to specific microfrontends
router.broadcast('data-updated', { id: 42 }, ['app-a', 'app-b']);

unloadAll(): void

Removes all iframes from the DOM.

router.unloadAll();

getOutletState(outlet?: string): OutletState

Returns the current state of the outlet, including the active route and all tracked routes. If no outlet name is provided, the default from the configuration is used.

const state = router.getOutletState();
console.log(state.activeRoute.metaRoute); // e.g., 'app-a'
console.log(state.activeRoute.subRoute);  // e.g., 'settings'

registerAllowStateDiscardCallbackAsync(callback, stateEvaluation?): void

Registers a callback invoked before navigating away from a microfrontend that has unsaved state. Return true from the callback to allow navigation, false to block it.

router.registerAllowStateDiscardCallbackAsync(
  async (metaRoute: string, subRoute?: string) => {
    return confirm(`Discard changes in ${metaRoute}?`);
  },
  MetaRouteStateEvaluation.RouteBased
);
Parameter Type Description
callback (metaRoute: string, subRoute?: string) => Promise<boolean> Async callback that returns whether to allow navigation
stateEvaluation MetaRouteStateEvaluation Optional. How to evaluate dirty state (default: RouteBased)

Properties

outletStateChanged?: OutletStateChanged

A callback invoked whenever the outlet state changes (active route, route list). Assign a function to receive state update notifications.

router.outletStateChanged = (state: OutletState) => {
  console.log(`Active: ${state.activeRoute.url}`);
};

MetaRouterConfig

Configuration class for MetaRouter.

import { MetaRouterConfig } from '@microfrontend/controller';

Constructor

constructor(
  outlet: string,
  routes: IAppConfig[],
  handleNotification: HandleBroadcastNotification,
  frameConfig?: FrameConfig,
  unknownRouteHandling?: UnknownRouteHandlingEnum,
  logLevel?: Level
)
Parameter Type Default Description
outlet string Required. Name of the outlet (must match the DOM element id)
routes IAppConfig[] Required. Array of microfrontend route configurations
handleNotification HandleBroadcastNotification Required. Callback for broadcast messages received by the shell
frameConfig FrameConfig new FrameConfig() Optional iframe configuration
unknownRouteHandling UnknownRouteHandlingEnum ThrowError How to handle unknown routes
logLevel Level Level.INFO Logging verbosity

Throws: Error if outlet is empty or routes is empty.


IAppConfig

Interface defining a microfrontend route.

import { IAppConfig } from '@microfrontend/controller';
Property Type Description
metaRoute string Unique identifier for the microfrontend (appears in the URL hash)
baseUrl string Entry point URL where the microfrontend is served
const route: IAppConfig = {
  metaRoute: 'dashboard',
  baseUrl: 'https://dashboard.example.com'
};

AppRoute

Represents a meta route with an optional subroute.

import { AppRoute } from '@microfrontend/controller';

Constructor

constructor(metaRoute: string, subRoute?: string)

Leading slashes in subRoute are automatically stripped. An empty subroute is treated as undefined.

Properties

Property Type Description
metaRoute string The meta route identifier
subRoute string | undefined The subroute within the microfrontend
url string Full URL: metaRoute or metaRoute/subRoute

Static Methods

AppRoute.fromUrl(url: string): AppRoute

Creates an AppRoute from a full route URL string.

const route = AppRoute.fromUrl('dashboard/settings');
// route.metaRoute === 'dashboard'
// route.subRoute === 'settings'

FrameConfig

Configuration for iframes created by the meta router.

import { FrameConfig } from '@microfrontend/controller';

Constructor

constructor(
  custom?: IMap<string>,
  styles?: IMap<string>,
  attributes?: IMap<string>,
  hashPrefix?: string
)
Parameter Type Default Description
custom IMap<string> {} Custom key-value data stored on the iframe (accessible by the microfrontend via requestCustomFrameConfiguration)
styles IMap<string> {} CSS styles applied to the iframe element
attributes IMap<string> {} HTML attributes set on the iframe element
hashPrefix string '/' Prefix prepended to hash routes

Forbidden values (throws Error):

  • styles must not contain display (managed internally for show/hide)
  • attributes must not contain style, src, id, or data-custom-config (managed internally)
const frameConfig = new FrameConfig(
  { apiKey: 'abc123' },                    // custom data
  { border: 'none', width: '100%' },       // styles
  { class: 'mf-frame', title: 'App A' },   // attributes
  '/'                                       // hash prefix
);

OutletState

Represents the state of an outlet at a given moment.

import { OutletState } from '@microfrontend/controller';

Properties

Property Type Description
outlet string The outlet name
routes AppRoute[] All routes tracked in this outlet
activeRoute AppRoute The currently active (visible) route — always routes[0]

MetaRouteStateEvaluation

Enum controlling how dirty state is evaluated.

import { MetaRouteStateEvaluation } from '@microfrontend/controller';
Value Description
RouteBased The microfrontend is considered dirty only if the active subroute has state. This is the default.
AppBased The microfrontend is considered dirty if any subroute has state.

UnknownRouteHandlingEnum

Enum controlling behavior when an unknown route is encountered.

import { UnknownRouteHandlingEnum } from '@microfrontend/controller';
Value Description
ThrowError Throws an error when navigating to an unknown route (default)
RedirectToFirstKnown Redirects to the first configured route

Clone this wiki locally