A base micro-frontend splits the port into what the elements use and what the host provides, and a factory does the wiring, so each micro-frontend only describes its own state, actions and services.

In the first post in this series we gave an order entry micro-frontend a port, so the same element could run in the shell, Storybook and a test harness with a different adapter in each. That works for one micro-frontend, but the adapter ended up doing more than connecting the micro-frontend to its host.

In this post we'll build a base micro-frontend that every micro-frontend in an app can share. It splits the port into what the elements use and what the host provides, and a factory does the wiring, so each micro-frontend only describes its own state, actions and services.

The adapter does too much

The shell adapter from part 1 creates the store, sets isSubmitting while a bid is in flight, calls the API, notifies the user of the outcome and updates the instrument when a message arrives from another micro-frontend. Only the API call and the shell services are specific to the shell. Everything else is how order entry behaves, and it's the same in every host.

To show the form submitting a bid in Storybook, or to test it in the harness, each adapter would have to repeat that behaviour. Copies drift, and a test that passes against the harness adapter's copy doesn't say much about the shell's.

Across every micro-frontend in an app, each team would also end up writing the same store, context and subscription code. The base micro-frontend takes all of that on:

The behaviour moves into the micro-frontend, and the adapter only supplies the services it depends on.

A port with two sides

Hexagonal architecture has two kinds of port. Driving ports are for whatever uses the application, such as a UI or a test, and driven ports are for whatever the application uses, such as a database or another service. The port in part 1 only had the driving side. It described how the elements use the micro-frontend, through state and actions, and left everything the micro-frontend needs from outside to the adapter.

The base micro-frontend's port describes both sides.

// micro-frontend/port.ts
import type { Context } from "@lit/context";

export interface Store<TState> {
  getState: () => TState;
  subscribe: (listener: () => void) => () => void;
}

// Driving side: what the micro-frontend's elements use
export interface MicroFrontendPort<TState, TActions> {
  store: Store<TState>;
  actions: TActions;
}

// Driven side: services every host provides, whatever the micro-frontend
export interface ShellServices {
  notifications: {
    success: (message: string) => void;
    error: (message: string) => void;
  };
  messages: {
    subscribe: <T>(topic: string, listener: (message: T) => void) => () => void;
  };
}

// What an adapter supplies to create a micro-frontend
export interface Adapter<TState, TServices> {
  services: TServices;
  shell: ShellServices;
  initialState?: Partial<TState>;
}

MicroFrontendPort has the same shape as the order entry port from part 1, a read-only store and some actions, with the state and actions as type parameters. ShellServices are the same for every micro-frontend in the app, so they're defined once in the base. services is whatever a particular micro-frontend needs from the backend, and initialState lets an adapter start the micro-frontend in a particular state, such as the instrument the shell opened it with.

Order entry fills in the type parameters.

// order-entry/port.ts
export type Bid = { instrumentId: string; price: number; quantity: number };

export type PriceTick = { instrumentId: string; price: number };

export type OrderEntryState = {
  instrumentId: string;
  price?: number;
  isSubmitting: boolean;
};

export type OrderEntryActions = {
  submitBid: (price: number, quantity: number) => void;
};

// What order entry needs from every host
export type OrderEntryServices = {
  orders: { submitBid: (bid: Bid) => Promise<void> };
  prices: {
    subscribe: (listener: (tick: PriceTick) => void) => () => void;
  };
};

Order entry now shows a live price for the instrument as well. The price can change many times a second, while the instrument and the form only change when the user does something. That difference matters when we connect elements to the store.

OrderEntryServices is the driven side of order entry's port. Order entry needs to submit a bid and receive prices, and the port doesn't say how either is done. The shell adapter uses the shell's REST API, Storybook can return canned prices and the test harness points at a mocked backend.

Defining a micro-frontend

With the port split in two, the behaviour that was in the part 1 adapter can move into the micro-frontend. Each micro-frontend describes itself with a definition: the element to create, the context its elements read the port from, its initial state and two functions that hold its behaviour.

// micro-frontend/port.ts (continued)

// What a micro-frontend's behaviour works with in any host
export type Runtime<TState, TServices> = {
  getState: () => TState;
  setState: (changes: Partial<TState>) => void;
  services: TServices;
  shell: ShellServices;
};

export type MicroFrontendDefinition<TState, TActions, TServices> = {
  tagName: string;
  context: Context<unknown, MicroFrontendPort<TState, TActions>>;
  initialState: TState;
  actions: (runtime: Runtime<TState, TServices>) => TActions;
  // Subscribes to sources outside the micro-frontend and returns a cleanup
  connect?: (runtime: Runtime<TState, TServices>) => () => void;
};

Both functions are given the same Runtime: the store's getState and setState, the services and the shell services. actions returns the actions the elements can call. connect subscribes to anything outside the micro-frontend that changes its state, and returns a function to clean up. Neither function knows which host it's running in, only that the host has supplied what the port asks for.

Here's order entry.

// order-entry/order-entry.ts
import { createContext } from "@lit/context";
import type {
  MicroFrontendDefinition,
  MicroFrontendPort,
} from "../micro-frontend/port";
import type {
  OrderEntryActions,
  OrderEntryServices,
  OrderEntryState,
} from "./port";

export const orderEntryContext = createContext<
  MicroFrontendPort<OrderEntryState, OrderEntryActions>
>(Symbol("order-entry"));

export const orderEntry: MicroFrontendDefinition<
  OrderEntryState,
  OrderEntryActions,
  OrderEntryServices
> = {
  tagName: "order-entry",
  context: orderEntryContext,
  initialState: { instrumentId: "", isSubmitting: false },

  actions: ({ getState, setState, services, shell }) => ({
    async submitBid(price, quantity) {
      setState({ isSubmitting: true });
      try {
        const { instrumentId } = getState();
        await services.orders.submitBid({ instrumentId, price, quantity });
        shell.notifications.success(`Bid submitted at ${price}`);
      } catch {
        shell.notifications.error("Bid could not be submitted");
      } finally {
        setState({ isSubmitting: false });
      }
    },
  }),

  connect: ({ getState, setState, services, shell }) => {
    const unsubscribePrices = services.prices.subscribe(
      ({ instrumentId, price }) => {
        // Ignore prices for instruments that aren't selected
        if (instrumentId === getState().instrumentId) setState({ price });
      },
    );
    const unsubscribeMessages = shell.messages.subscribe(
      "instrument-selected",
      ({ instrumentId }: { instrumentId: string }) =>
        setState({ instrumentId, price: undefined }),
    );

    return () => {
      unsubscribePrices();
      unsubscribeMessages();
    };
  },
};

submitBid is the code from the part 1 adapter, with the API call swapped for the orders service. It now takes a price and a quantity and adds the selected instrument itself, so the form doesn't need to know which instrument is selected. connect updates the instrument when another micro-frontend selects one, and only keeps prices for the selected instrument.

This is how order entry behaves in every host, written once. It's also plain TypeScript, so it can be tested by calling actions and connect with fake services and a store, with no elements, DOM or host involved.

Creating micro-frontends with a factory

The factory puts a micro-frontend's definition and an adapter together.

// micro-frontend/create.ts
import { ContextProvider } from "@lit/context";
import { createStore } from "./create-store";
import type { Adapter, MicroFrontendDefinition } from "./port";

export function createMicroFrontend<TState extends object, TActions, TServices>(
  definition: MicroFrontendDefinition<TState, TActions, TServices>,
  container: HTMLElement,
  adapter: Adapter<TState, TServices>,
) {
  const { getState, setState, subscribe } = createStore<TState>({
    ...definition.initialState,
    ...adapter.initialState,
  });
  const { services, shell } = adapter;
  const runtime = { getState, setState, services, shell };
  const disconnect = definition.connect?.(runtime);

  new ContextProvider(container, {
    context: definition.context,
    initialValue: {
      // Elements can read the store but not write to it
      store: { getState, subscribe },
      actions: definition.actions(runtime),
    },
  });
  container.append(document.createElement(definition.tagName));

  return () => {
    disconnect?.();
    container.replaceChildren();
  };
}

createMicroFrontend is what a host calls. It creates the store from the definition's initial state, with any initial state from the adapter on top, and builds a runtime from the store and the adapter's services for actions and connect. Then it provides the port to the container and appends the micro-frontend's element, the same steps as the part 1 adapter but written once for every micro-frontend. The store in the port only has getState and subscribe, so elements can read state but only the micro-frontend's logic can change it, and concrete micro-frontends never create or dispose of a store themselves.

Diagram showing an adapter supplying services and shell services, and order entry's definition supplying state, actions and connect, to the createMicroFrontend factory. The factory creates the port, which order entry's elements read through StoreController via context.
The factory builds the port from a micro-frontend's definition and the parts an adapter supplies

Controllers that select state

The part 1 controller was written for order entry. It requested an update whenever the store changed, which was fine while the form used every property in the state. With a live price in the state, the form would update on every tick even though it doesn't show the price.

StoreController replaces it for every micro-frontend. It takes the micro-frontend's context and a function that selects the slice of state the element reads, and only requests an update when that slice changes.

// micro-frontend/store-controller.ts
import { ContextConsumer, type Context } from "@lit/context";
import type { ReactiveController, ReactiveElement } from "lit";
import type { MicroFrontendPort } from "./port";

export class StoreController<
  TState,
  TActions,
  TSlice,
> implements ReactiveController {
  value!: TSlice;
  #port: ContextConsumer<
    Context<unknown, MicroFrontendPort<TState, TActions>>,
    ReactiveElement
  >;
  #unsubscribe?: () => void;

  constructor(
    private host: ReactiveElement,
    context: Context<unknown, MicroFrontendPort<TState, TActions>>,
    private select: (state: TState) => TSlice,
  ) {
    this.#port = new ContextConsumer(host, { context });
    host.addController(this);
  }

  get actions() {
    return this.#port.value!.actions;
  }

  hostConnected() {
    const { store } = this.#port.value!;
    this.value = this.select(store.getState());
    this.#unsubscribe = store.subscribe(() => {
      const value = this.select(store.getState());
      // Only update the element when its slice of state changes
      if (Object.is(value, this.value)) return;
      this.value = value;
      this.host.requestUpdate();
    });
  }

  hostDisconnected() {
    this.#unsubscribe?.();
  }
}

Order entry now has two elements. <order-entry-price> selects the price and <order-entry> selects isSubmitting.

// order-entry/elements.ts
import { LitElement, html } from "lit";
import { customElement } from "lit/decorators.js";
import { StoreController } from "../micro-frontend/store-controller";
import { orderEntryContext } from "./order-entry";

@customElement("order-entry-price")
export class OrderEntryPrice extends LitElement {
  #price = new StoreController(this, orderEntryContext, (s) => s.price);

  render() {
    return html`<output>${this.#price.value ?? "โ€“"}</output>`;
  }
}

@customElement("order-entry")
export class OrderEntry extends LitElement {
  #orderEntry = new StoreController(
    this,
    orderEntryContext,
    (s) => s.isSubmitting,
  );

  #onSubmit(event: SubmitEvent) {
    event.preventDefault();
    const form = new FormData(event.target as HTMLFormElement);
    this.#orderEntry.actions.submitBid(
      Number(form.get("price")),
      Number(form.get("quantity")),
    );
  }

  render() {
    return html`
      <form @submit=${this.#onSubmit}>
        <order-entry-price></order-entry-price>
        <label>
          Bid price
          <input name="price" type="number" min="0" step="any" required />
        </label>
        <label>
          Quantity
          <input name="quantity" type="number" min="1" required />
        </label>
        <button ?disabled=${this.#orderEntry.value}>Submit bid</button>
      </form>
    `;
  }
}

A price tick updates <order-entry-price> and not the form. Selecting another instrument clears the price, which updates <order-entry-price> again, and the form still doesn't update because isSubmitting hasn't changed.

This is what the external store is for. The price and the instrument change because of things that happen outside the elements, a price service and a message from another micro-frontend, so the state can't live in an element. Keeping it in a store the micro-frontend owns means every element subscribes to the same state, and each one only updates for the part it shows.

The shell adapter, again

With the behaviour in the micro-frontend, the shell adapter from part 1 is left with the parts that are specific to the shell.

// shell-adapter/mount-order-entry.ts
import { api } from "@shell/api";
import { messages } from "@shell/messages";
import { notifications } from "@shell/notifications";
import { createMicroFrontend } from "../micro-frontend/create";
import { orderEntry } from "../order-entry/order-entry";

export function mountOrderEntry(container: HTMLElement, instrumentId: string) {
  return createMicroFrontend(orderEntry, container, {
    services: {
      orders: {
        submitBid: async (bid) => void (await api.post("/orders/bids", bid)),
      },
      prices: {
        subscribe: (listener) => api.stream("/prices", listener),
      },
    },
    shell: { notifications, messages },
    initialState: { instrumentId },
  });
}

It turns the shell's REST API into the orders and prices services, passes on the shell's notifications and messages, and starts order entry on the instrument the shell opened it with. There's no store, no context and no isSubmitting, and nothing in it describes how order entry behaves. Storybook and the test harness supply their own services in the same way.

What's next

Order entry is now defined once, and an adapter only has to supply the services it needs. In part 3 we'll write the other two adapters. Storybook gets services that never touch a network, so a story can show a bid mid-submission or a rejected bid with order entry's own logic running. The test harness uses the shell's REST services against a mocked backend, which gives us two tiers of end-to-end tests and a cost that's easy to miss: keeping the test data in step between them.