Courses / Frontend System Design, with JavaScript Foundations / Chapter 13
Module 6 · Patterns, Architecture and Security · Chapter 13 of 21
Frontend Design Patterns and Architectures
Builds on this, Prototypes and Classes, The DOM, Events and Observers, Non-functional Requirements, Frontend Fundamentals: Components, State, Data and Rendering and API Styles, Protocols and Data Formats. Next up: Security in Frontend Systems.
Part 1 · Code patterns in frontend work
Observer
Frontend code keeps returning to a few shapes. Naming them lets a team describe a design in a sentence, and lets you recognise the shape inside a library you did not write.
A design pattern is a named, reusable answer to a problem that keeps coming up. It is not a library you install. It is a way to arrange code, and the same pattern can be written in any language. This lesson covers five that matter in browser code: observer, module, singleton, proxy and factory. Each one is run in Node.
The observer pattern lets one object announce that something happened without knowing who is listening. The object that announces is the subject, and the listeners are observers. A product page needs this the moment two parts of the screen depend on one number: the stock badge and the alert box both change when stock changes, and neither should know about the other.
The browser already ships the pattern as EventTarget, the same interface that elements use. Node has it too, so the script below runs unchanged. It registers two listeners, then removes one with the signal option that the DOM chapter introduced.
const bus = new EventTarget() const badge = (e) => console.log('badge: stock is', e.detail.left) const alertBox = (e) => console.log('alert: stock is', e.detail.left) const stop = new AbortController() bus.addEventListener('stock', badge) bus.addEventListener('stock', alertBox, { signal: stop.signal }) const publish = (left) => bus.dispatchEvent(new CustomEvent('stock', { detail: { left } })) publish(9) stop.abort() // the alert box is gone from the page publish(8)
observer.mjs: two observers of one subject.
badge: stock is 9 alert: stock is 9 badge: stock is 8
Output (Node 24)
The first update reached both listeners. After stop.abort() only the badge heard the second one. The store in the fundamentals chapter, with its subscribe function that returns an unsubscribe function, is the same pattern with a state object attached. Observers that are never removed are a classic memory leak, which is why every subscription should come with a way to end it.
Module and singleton
The module pattern keeps some state private and exposes only a small set of functions. Before the language had modules, code did this with a function that returned an object. Today an ES module does it directly: names that are not exported cannot be reached from outside.
let count = 0 // private: not exported export function increment() { return ++count } export const read = () => count
counter.mjs: `count` is private.
import { increment, read } from './counter.mjs' increment() increment() console.log('read():', read()) try { await import('./uses-private.mjs') } catch (err) { console.log(err.name + ':', err.message) }
module-use.mjs: the public functions work, the private name does not.
import { count } from './counter.mjs' console.log(count)
uses-private.mjs: tries to import the private name.
read(): 2 SyntaxError: The requested module './counter.mjs' does not provide an export named 'count'
Output (Node 24)
The two calls to increment() show through read(), so the state is real. Importing count fails before any code runs, because the module's export list is checked first. A caller can only change the counter through the door you built.
A singleton is an object that exists once. An app has one configuration, one analytics client, one connection to a server. ES modules give you this for free: a module is evaluated once per URL, and every importer gets the same objects. The script imports the same module three times, the third time with a different query string.
export const config = { apiBase: 'https://api.example.com', calls: 0 }
config.mjs: the shared object.
const a = await import('./config.mjs') const b = await import('./config.mjs') const c = await import('./config.mjs?copy=2') // a different URL a.config.calls++ console.log('a and b are the same object:', a.config === b.config) console.log('b.calls:', b.config.calls) console.log('c is the same object:', a.config === c.config) console.log('c.calls:', c.config.calls)
singleton.mjs: three imports of one file.
a and b are the same object: true b.calls: 1 c is the same object: false c.calls: 0
Output (Node 24)
a and b are the same object, so the increment through a shows in b. c came from a different URL, so the module ran again and produced a second object with its own counter. This is how a page that loads two copies of the same library ends up with two singletons that do not know about each other. Bundlers do the same when two bundles each include the module, and the micro frontends lesson measures what the duplication costs in bytes.
Proxy and factory
A proxy wraps an object and intercepts what is done to it: reading a property, writing one, deleting one. The language has a built-in Proxy for this. A proxy can validate writes, log reads, or track which properties a function touched. Some frameworks use exactly this to notice when state changes without being told.
const cart = { items: 2 } const guarded = new Proxy(cart, { get(target, key, receiver) { console.log('read ', String(key)) return Reflect.get(target, key, receiver) }, set(target, key, value, receiver) { if (key === 'items' && !(Number.isInteger(value) && value >= 0)) { throw new RangeError(`items must be a whole number, got ${value}`) } return Reflect.set(target, key, value, receiver) }, }) guarded.items = 5 console.log('items is', guarded.items) try { guarded.items = -1 } catch (err) { console.log(err.name + ':', err.message) } console.log('the target still holds', cart.items)
proxy.mjs: a cart that refuses nonsense and logs reads.
read items items is 5 RangeError: items must be a whole number, got -1 the target still holds 5
Output (Node 24)
The setter ran for items = 5 and let it through. For -1 it threw, and the original object kept its value. A proxy costs an extra function call on every operation, and objects with private fields behave differently through one: the classes chapter showed that #x is not reachable through a proxy. Use it where interception is the point, not as a default wrapper.
A factory is a function that returns a ready-made object so that callers do not decide how it is built. The factory below picks a number formatter by currency and returns a small function. Callers pass a code and never touch Intl options.
const inr = { style: 'currency', currency: 'INR' } const usd = { style: 'currency', currency: 'USD' } const money = { inr: new Intl.NumberFormat('en-IN', inr), usd: new Intl.NumberFormat('en-US', usd), } function createPriceTag(currency) { const fmt = money[currency] if (!fmt) throw new Error(`no formatter for ${currency}`) return (amount) => fmt.format(amount) } const rupees = createPriceTag('inr') const dollars = createPriceTag('usd') console.log(rupees(1234567.5)) console.log(dollars(1234567.5)) try { createPriceTag('eur') } catch (err) { console.log(err.message) }
factory.mjs: a price tag per currency.
₹12,34,567.50 $1,234,567.50 no formatter for eur
Output (Node 24)
Part 2 · Component patterns
Separating logic from view
A page is built from components, and a few arrangements of them come up again and again. This lesson names four of them and runs one in Chrome.
The oldest arrangement is container and presentational. A presentational component takes data and callbacks as inputs and draws markup. It does not fetch anything and does not know where its data came from. A container component does the fetching, holds the state, and passes the results down. Splitting them keeps the drawing code easy to test with fixed data and easy to reuse on another screen.
Modern frameworks let you put the logic in reusable functions instead of a container component, so the strict two-component split is less common. The separation of concerns it taught is not: whatever the form, keep the code that decides what the data is apart from the code that decides how it looks.
The sharpest form of that idea is the headless component. It supplies behaviour with no markup and no styling at all. A tab list, for example, has rules that do not depend on how it looks: which tab is selected, what the arrow keys do, what happens at the ends. The rules live in a plain function, and every visual design reuses them.
// Headless: the rules of a tab list, with no DOM and no styling. export function nextTab(count, current, key) { if (key === 'ArrowRight') return (current + 1) % count if (key === 'ArrowLeft') return (current - 1 + count) % count if (key === 'Home') return 0 if (key === 'End') return count - 1 return current // any other key changes nothing }
tabs-logic.mjs: the rules of a tab list, with no DOM.
import { nextTab } from './tabs-logic.mjs' for (const [current, key] of [[0, 'ArrowRight'], [2, 'ArrowRight'], [0, 'ArrowLeft'], [1, 'End'], [2, 'Home'], [1, 'a']]) { console.log(`3 tabs, on ${current}, ${key.padEnd(10)} ->`, nextTab(3, current, key)) }
tabs-node.mjs: the rules checked in Node.
3 tabs, on 0, ArrowRight -> 1 3 tabs, on 2, ArrowRight -> 0 3 tabs, on 0, ArrowLeft -> 2 3 tabs, on 1, End -> 2 3 tabs, on 2, Home -> 0 3 tabs, on 1, a -> 1
Output (Node 24)
Because it is only a function, the rules can be tested without a browser. The arrows wrap round, Home and End jump to the ends, and any other key changes nothing. Whoever builds the visible tabs has to follow the same rules, which is the point.
Compound components
A compound component is a group of components that work together and share an implicit state. HTML itself has them: a select and its option elements, or a ul and its li elements. You never pass the selected option to each option. The parent holds the state, and the children are written inside it.
The tabs below are a compound component built as web components. The page author writes the markup, and ui-tabs connects the pieces: it gives each tab and panel an id, links them with aria-controls and aria-labelledby, keeps only the selected panel visible, and uses the headless function for the keyboard.
<!doctype html> <html lang="en"> <title>Tabs</title> <ui-tabs> <div role="tablist" aria-label="Account"> <ui-tab>Orders</ui-tab> <ui-tab>Returns</ui-tab> <ui-tab>Payments</ui-tab> </div> <ui-panel>Three open orders</ui-panel> <ui-panel>One return in progress</ui-panel> <ui-panel>No payments due</ui-panel> </ui-tabs>
tabs-page.html: the markup the page author writes.
<script type="module"> import { nextTab } from './tabs-logic.mjs' class UiTabs extends HTMLElement { connectedCallback() { this.tabs = [...this.querySelectorAll('ui-tab')] this.panels = [...this.querySelectorAll('ui-panel')] this.tabs.forEach((tab, i) => { tab.setAttribute('role', 'tab') tab.id = `tab-${i}` tab.setAttribute('aria-controls', `panel-${i}`) this.panels[i].id = `panel-${i}` this.panels[i].setAttribute('role', 'tabpanel') this.panels[i].setAttribute('aria-labelledby', tab.id) tab.addEventListener('click', () => this.select(i)) tab.addEventListener('keydown', (e) => { const to = nextTab(this.tabs.length, i, e.key) if (to !== i) { e.preventDefault(); this.select(to, true) } }) }) this.select(0) }
tabs-page.html: the parent wires up the children.
select(index, focus = false) {
this.tabs.forEach((tab, i) => {
tab.setAttribute('aria-selected', String(i === index))
tab.tabIndex = i === index ? 0 : -1 // roving tabindex
this.panels[i].hidden = i !== index
})
if (focus) this.tabs[index].focus()
}
}
customElements.define('ui-tabs', UiTabs)
customElements.define('ui-tab', class extends HTMLElement {})
customElements.define('ui-panel', class extends HTMLElement {})
</script>tabs-page.html: selecting, and registering the elements.
The state is the selected index. select updates three things together: aria-selected on every tab, a roving tabindex so that only the selected tab is in the page's tab order (the arrow keys move between the others), and the hidden attribute on the panels. The page author never mentions any of this. Chrome loads the page from a local server and a script clicks and presses keys.
Slots and composition
The last pattern is about how a parent gives a component content. A component can take props, small values such as a title or a count. Or it can take slots: places where the parent puts its own markup. The fundamentals chapter built a rating element with a label slot.
Props suit values the component must understand, such as a number it formats. Slots suit content the component only has to place. A card with a title prop, a subtitle prop, an image prop, a footer prop, an actions prop and a badge prop is a sign that the content should have been slots. Each new prop is a new decision for every caller, while a slot lets them pass anything, including another component.
| Arrangement | What it gives you | Watch out for |
|---|---|---|
| Container and presentational | data logic apart from drawing | extra files for tiny screens |
| Headless component | behaviour reused under any design | every caller must supply markup |
| Compound components | a clean API for related parts | children outside the parent break silently |
| Slots and children | flexible content, few props | less control over what is inserted |
These arrangements are the same in React, Vue, Angular and plain web components, with different syntax. React calls slots children or render props, Vue has named slots, and web components have the slot element.
The cost of compound components is that they rely on structure. If a ui-tab is placed outside a ui-tabs, nothing wires it up and nothing warns you. A good compound component checks its children and reports the mistake, or documents the structure it expects.
Part 3 · One-way data flow
Why data should flow one way
When a screen has many parts that can all change shared data, finding out why a number changed becomes the main cost of the code. One-way data flow is the main way frontends keep that cost under control.
Imagine two-way flow. A form field changes a model, the model changes a list, the list changes a total, and the total changes the form field's validation. Any part can reach any other, so a bug could come from anywhere. In one-way data flow data moves in one direction only: state goes down to the views, and the views send actions, plain descriptions of what happened, back up. Views never write to the state directly.
Facebook described this style as Flux: actions go to a dispatcher, then to stores, then to views. The Flux repository is archived and read-only since 23 March 2023, and its README points users to Redux, MobX, Recoil, Zustand and Jotai instead. The ideas outlived it. The most widely copied piece is the reducer, a pure function that takes the current state and an action and returns the next state.
A pure function has no side effects and always returns the same result for the same input. That gives you three things at once: you can replay a list of actions to rebuild any state, you can test a reducer with plain data, and you can tell whether anything changed by comparing references.
const initial = { items: [], coupon: null } function reducer(state, action) { switch (action.type) { case 'item-added': return { ...state, items: [...state.items, action.item] } case 'item-removed': return { ...state, items: state.items.filter((i) => i.id !== action.id) } case 'coupon-applied': return { ...state, coupon: action.code } default: return state } }
flow.mjs: a reducer.
A store you can run
The store holds the state, runs the reducer on each action and notifies subscribers. It freezes the state so that a view that tries to change it directly fails loudly. Unknown actions return the same state object, so nobody is notified.
const deepFreeze = (o) => { for (const v of Object.values(o)) { if (v && typeof v === 'object') deepFreeze(v) } return Object.freeze(o) } function createStore(reduce, start) { let state = deepFreeze(start) const listeners = new Set() return { getState: () => state, dispatch(action) { const next = reduce(state, action) if (next === state) return state = deepFreeze(next) listeners.forEach((fn) => fn(state, action)) }, subscribe: (fn) => (listeners.add(fn), () => listeners.delete(fn)), } }
flow.mjs: the store.
const store = createStore(reducer, initial) const history = [] store.subscribe((state, action) => { history.push(action) const total = state.items.reduce((sum, i) => sum + i.paise, 0) console.log(action.type.padEnd(15), 'items:', state.items.length, 'total paise:', total, 'coupon:', state.coupon) }) store.dispatch({ type: 'item-added', item: { id: 1, paise: 18000 } }) store.dispatch({ type: 'item-added', item: { id: 2, paise: 36500 } }) store.dispatch({ type: 'coupon-applied', code: 'FEST10' }) store.dispatch({ type: 'unknown' }) // no change, no notice store.dispatch({ type: 'item-removed', id: 1 })
flow.mjs: a view that logs, then actions.
const replayed = history.reduce(reducer, initial) console.log('replayed from the log:', JSON.stringify(replayed)) console.log('same as the store :', JSON.stringify(replayed) === JSON.stringify(store.getState())) const shallow = Object.freeze({ items: [1] }) shallow.items.push(2) // a shallow freeze lets this in console.log('shallow freeze, items:', shallow.items.length) try { store.getState().items.push({ id: 9, paise: 1 }) // a view cheating console.log('mutated:', store.getState().items.length) } catch (err) { console.log(err.name + ':', err.message) }
flow.mjs: replaying the log, and a view that cheats.
item-added items: 1 total paise: 18000 coupon: null item-added items: 2 total paise: 54500 coupon: null coupon-applied items: 2 total paise: 54500 coupon: FEST10 item-removed items: 1 total paise: 36500 coupon: FEST10 replayed from the log: {"items":[{"id":2,"paise":36500}],"coupon":"FEST10"} same as the store : true shallow freeze, items: 2 TypeError: Cannot add property 1, object is not extensible
Output (Node 24)
Each action produced one line. The unknown action produced nothing, because the reducer returned the same object. The last four lines are the payoff. Replaying the logged actions on the initial state rebuilt the exact same state. That is what makes undo, debugging by replay and server-driven sync possible.
Where the ideas went
Two older names describe the same problem from different angles. Model-view-controller (MVC) splits an app into the model that holds data, the view that shows it, and a controller that turns input into changes to the model. Model-view-viewmodel (MVVM) puts an object between model and view, the view-model, which exposes the data in the shape the view needs, and often binds it to the view in both directions. Binding saves code and makes it harder to see which of two parts caused a change, which is the problem one-way flow was meant to solve.
The newest answer is signals. A signal is a value that remembers which computations read it, so that setting it re-runs only those computations instead of re-rendering a whole component. Several frameworks, among them Solid and Angular, build their reactivity on signals. Signals still move data in one direction, from the value to what depends on it. The difference from a reducer store is how fine the updates are.
| Approach | How changes travel | Trade-off |
|---|---|---|
| Two-way binding | view and model update each other | less code, harder to trace |
| Reducer store | action, reducer, new state, views | more code, every change is a logged event |
| Signals | a value notifies what read it | fine-grained updates, less history |
You rarely need to name a library to explain this part. Say where state lives, how it changes, and how a change reaches the screen. A reducer store makes those three answers easy to give. Whatever you choose, keep the rule that a view only reads state and reports events.
What property of a reducer lets you rebuild a state from a log of actions?
- It is pure: the same state and action always give the same next state, with no side effects.
Part 4 · Application shapes
Four shapes of web application
Before choosing components or state tools, a team chooses the shape of the whole application. Four shapes cover most products, and they differ mainly in how much JavaScript runs and where HTML is produced.
A single-page application (SPA) loads one HTML document and then changes the screen with JavaScript, so moving between pages needs no new document. A multi-page application (MPA) is the older web: each link loads a new document from the server. The other two shapes, an island page and SSR with streaming, are rendering modes from the fundamentals chapter.
| Shape | First paint | Code the browser runs | Moving between pages | Complexity |
|---|---|---|---|---|
| SPA | late: code and data first | the whole app | fast, no new document | routing, state, SEO work |
| MPA | early: finished HTML | little, per page | a new document each time | low |
| Islands | early: finished HTML | only the interactive parts | a new document, or a router | two models in one page |
| SSR with streaming | early shell, content follows | everything for hydration | fast after the first load | servers and hydration |
An island you can run
The word island comes from a simple idea: do not ship code for the parts of a page that never change. Astro, an islands framework, renders components to plain HTML and removes the JavaScript by default. A client:* directive then marks a component as interactive. Per its documentation, client:load loads and hydrates the component immediately on page load, client:idle once the page has finished its initial load and the browser is idle, and client:visible once the component enters the viewport. A server:defer directive turns a component into a server island: it renders on the server separately from the page, which can be sent with placeholder content first.
You do not need the framework to see the mechanism. The page below is thirty paragraphs of server-written HTML followed by a reviews section. The reviews text is already in the HTML. A small inline script waits until the section is near the viewport, then loads the code that adds the working Helpful button. That is client:visible, written by hand.
const pageHtml = `<!doctype html><html lang="en"><title>Island</title> <article>${filler}</article> <section id="reviews" data-island="/reviews.js"> <h2>Reviews</h2> <p>Good tea, fresh and strong. <button hidden>Helpful</button> <span class="count"></span></p> </section> <script> const el = document.querySelector('[data-island]') new IntersectionObserver((entries, io) => { if (!entries.some((e) => e.isIntersecting)) return io.disconnect() import(el.dataset.island).then((m) => m.hydrate(el)) }, { rootMargin: '200px' }).observe(el) </script>`
island-server.mjs: the page, with its observer.
const islandJs = `export function hydrate(el) { const btn = el.querySelector('button') const out = el.querySelector('.count') let n = 0 btn.hidden = false btn.addEventListener('click', () => { out.textContent = '(' + ++n + ')' }) }`
island-server.mjs: the code of the island.
A Playwright script opens the page in a narrow Chrome window, lists the requests, scrolls to the reviews and clicks the button twice. A second browser context with JavaScript turned off reads the same section.
export const server = http.createServer((req, res) => { if (req.url === '/') { res.setHeader('content-type', 'text/html; charset=utf-8') return res.end(pageHtml) } if (req.url === '/reviews.js') { res.setHeader('content-type', 'text/javascript') return res.end(islandJs) } res.statusCode = 204 res.end() })
island-server.mjs: the server hands out the page and the island.
Choosing a shape
Choose from what the product does, not from habit. Three questions decide most cases.
- Is the content read more than it is changed? Articles, product pages and marketing pages are read-heavy. Server-rendered HTML or islands put the content on screen first.
- Does the user stay and work? A dashboard, an editor or a mail client keeps the user for an hour and fetches data on nearly every click. An SPA pays its start-up cost once and then moves fast.
- Does search or sharing matter? Pages that must be found and previewed need their content in the first HTML response, which favours server rendering, static pages or islands.
Mixed products are normal. A shopping site can serve product and category pages as server-rendered HTML with a few islands, and the account area as an SPA. The boundary between the two is a design decision, and a link across it is a full page load.
Whichever shape you choose, set a budget for the JavaScript that must run before the page responds, as the fundamentals chapter advised. The shapes differ in where the cost lands, not in whether it exists.
A recipe site is read far more than it is edited, and its readers arrive from search. Which shape fits and why?
- Server-rendered HTML or islands: the content is in the first response, and only a few widgets need code.
- An SPA would show a blank page until its script ran.
In the run, why was /reviews.js not requested before scrolling?
- The inline script only loads the island when an observer reports the section near the viewport.
- Until then the section is plain HTML and costs no code.
What does a page built from islands do when JavaScript is turned off?
- The server-written content is still shown.
Part 5 · Micro frontends
What they are and the ways to build them
A large product can have many teams working on one screen. Micro frontends split the screen into independently built and released parts so that those teams do not have to ship together.
A micro frontend is a part of a web page, owned by one team, that is built and deployed on its own and composed with others into one product. A page might be assembled from search, cart and reviews, each with its own repository, pipeline and release schedule. The page that assembles them is the shell or container. The approach borrows from microservices, and Martin Fowler's article on the subject is the standard description.
| Integration | How the parts are joined | Notes |
|---|---|---|
| Build time | each part is published as a package and the shell depends on it | any change means rebuilding and releasing everything |
| Server side | a server assembles HTML fragments from each team | familiar, HTML arrives finished, interactivity comes from other scripts |
| Run time, iframes | each part is a page inside a frame | strong isolation, awkward routing and layout |
| Run time, JavaScript | the shell loads each part's script and calls an entry point | flexible, the usual default choice |
| Run time, web components | each part is a custom element | uses browser features, parts are loosely coupled |
Build-time integration is the one Fowler's article advises against, because it forces a lockstep release: changing one part means rebuilding and releasing all of them, which removes the independence the split was meant to give. The run-time options keep each team's release separate.
The price of duplication
Each part is built on its own, so each part bundles its own copy of any library it uses. The lab uses a real library, DOMPurify, a library that removes dangerous markup from an HTML string. Three tiny micro frontends each import it and sanitise one string. esbuild builds them twice and reports from its metafile how many bytes of each output come from the library: first with each part bundling its own copy, then with the library left out.
import { build } from 'esbuild' import { statSync } from 'node:fs' const names = ['cart', 'search', 'reviews'] async function run(dir, label, external) { const result = await build({ entryPoints: names.map((n) => `src/${n}.js`), outdir: dir, bundle: true, minify: true, format: 'esm', metafile: true, external, logLevel: 'silent', }) let total = 0 console.log(`-- ${label}`) for (const [file, out] of Object.entries(result.metafile.outputs)) { const lib = Object.entries(out.inputs) .filter(([name]) => name.includes('dompurify')) .reduce((sum, [, v]) => sum + v.bytesInOutput, 0) total += out.bytes console.log(file.padEnd(16), String(out.bytes).padStart(6), 'bytes, dompurify inside:', lib) } console.log('total'.padEnd(16), String(total).padStart(6), 'bytes') return total }
build.mjs: two builds, each measured.
await run('own', 'each one bundles its own copy', []) const apps = await run('shared', 'dompurify left out', ['dompurify']) await build({ entryPoints: ['../node_modules/dompurify/dist/purify.es.mjs'], outfile: 'shared/purify.js', bundle: true, minify: true, format: 'esm', }) const lib = statSync('shared/purify.js').size console.log('one shared copy', String(lib).padStart(6), 'bytes') console.log('apps + one copy', String(apps + lib).padStart(6), 'bytes')
build.mjs: one shared copy, and the totals.
-- each one bundles its own copy own/cart.js 31242 bytes, dompurify inside: 30701 own/search.js 31240 bytes, dompurify inside: 30701 own/reviews.js 31247 bytes, dompurify inside: 30701 total 93729 bytes -- dompurify left out shared/cart.js 139 bytes, dompurify inside: 0 shared/search.js 137 bytes, dompurify inside: 0 shared/reviews.js 144 bytes, dompurify inside: 0 total 420 bytes one shared copy 31148 bytes apps + one copy 31568 bytes
Output (Node 24)
Each of the three bundles is about 31 KB, and about 30.7 KB of every one is the library. Three parts cost 93,729 bytes. With the library left out, the three parts are about 420 bytes together and one shared copy of the library is 31,148 bytes, so the page downloads 31,568 bytes instead of 93,729. These are uncompressed sizes for one library on this machine. The point is the shape: duplication grows with the number of parts.
Composing at run time, and when a part fails
The shell below uses the run-time JavaScript approach. It reads a table of remotes, loads each with import() and calls its mount function. Each load is wrapped in try and catch, so a part that fails to load leaves a fallback message and does not break the rest of the page.
<title>Shell</title> <script type="importmap"> { "imports": { "dompurify": "/shared/purify.js" } } </script> <header>Shop shell</header> <main> <section id="search"></section> <section id="cart"></section> <section id="reviews"></section> </main> <script type="module"> const remotes = { search: '/shared/search.js', cart: '/shared/cart.js', reviews: '/shared/reviews.js', } window.report = {} await Promise.all(Object.entries(remotes).map(async ([name, url]) => { const el = document.getElementById(name) try { const mod = await import(url) mod.mount(el) window.report[name] = 'mounted' } catch (err) { el.textContent = `${name} is unavailable right now` window.report[name] = 'fallback' } })) </script>
shell.html: the import map, the regions and the loader.
The server delivers the shared files, but deliberately answers 500 for the reviews part. Chrome loads the page and the script prints what each region shows.
const seen = [] const server = http.createServer((req, res) => { seen.push(req.url) if (req.url === '/') { res.setHeader('content-type', 'text/html; charset=utf-8') return res.end(readFileSync('shell.html')) } if (req.url === '/shared/reviews.js') { // this remote is down res.statusCode = 500 return res.end('upstream error') } const file = '.' + req.url if (req.url.startsWith('/shared/') && existsSync(file)) { res.setHeader('content-type', 'text/javascript') return res.end(readFileSync(file)) } res.statusCode = 204 res.end() }) await new Promise((r) => server.listen(55809, '127.0.0.1', r))
shell-run.mjs: the server, with one remote down.
const browser = await chromium.launch({ executablePath: CHROME }) const page = await browser.newPage() await page.goto('http://127.0.0.1:55809/') await page.waitForFunction( () => Object.keys(window.report).length === 3) for (const name of ['search', 'cart', 'reviews']) { const text = await page.locator('#' + name).innerText() const how = await page.evaluate((n) => window.report[n], name) console.log(name.padEnd(8), how.padEnd(9), JSON.stringify(text)) } console.log('cart markup:', await page.locator('#cart').innerHTML()) console.log('dompurify requests:', seen.filter((u) => u === '/shared/purify.js').length) await browser.close() server.close()
shell-run.mjs: the browser and the report.
Part 6 · Design systems and monorepos
Tokens, components and who owns them
When several teams build screens for one product, the buttons, colours and spacing drift apart. A design system is the shared set of decisions and parts that stops this.
A design system has three layers. Design tokens are named values for the decisions that rarely change: a brand colour, a spacing step, a corner radius. A component library is code for the building blocks that use those tokens, such as a button or a tab list. Guidelines explain when to use each one. The tokens are the base: a colour is defined once, and everything that uses it follows.
A token file is data, so a script can turn it into whatever each platform needs. The script below reads one JSON file and writes CSS custom properties. The same file could feed an Android or iOS build.
{
"color": {
"text": "#1f2933",
"surface": "#ffffff",
"brand": "#0b6e4f",
"brand-text": "#ffffff",
"muted": "#9aa5b1"
},
"space": { "1": "4px", "2": "8px", "3": "16px" },
"radius": { "button": "6px" }
}tokens.json: the decisions, as data.
import { readFileSync, writeFileSync } from 'node:fs' const tokens = JSON.parse(readFileSync('tokens.json', 'utf8')) // 1. tokens -> CSS custom properties const lines = [] for (const [group, values] of Object.entries(tokens)) { for (const [name, value] of Object.entries(values)) { lines.push(` --${group}-${name}: ${value};`) } } const css = `:root {\n${lines.join('\n')}\n}\n` writeFileSync('tokens.css', css) console.log(css)
build-tokens.mjs: tokens to CSS custom properties.
:root {
--color-text: #1f2933;
--color-surface: #ffffff;
--color-brand: #0b6e4f;
--color-brand-text: #ffffff;
--color-muted: #9aa5b1;
--space-1: 4px;
--space-2: 8px;
--space-3: 16px;
--radius-button: 6px;
}Output (Node 24), the generated CSS
The output is the same text the script wrote to tokens.css. Every page and component that uses var(--color-brand) now follows the one value in the JSON file.
Checking the system automatically
A rule written in a guide is easy to break. A rule checked by the build is not. The second half of the same script checks every foreground and background pair against the WCAG contrast rule from the requirements chapter: body text needs a ratio of at least 4.5 to 1. It computes the ratio from the relative luminance of each colour and fails the build if any pair is below the limit. The constants come from the WCAG 2.2 definition of relative luminance, which uses 0.04045 as the cut-off for the linear part of the curve; older text had 0.03928, and WCAG notes the difference has no practical effect here.
// 2. WCAG contrast ratio between two colours const channel = (c) => { const v = c / 255 return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4 } const luminance = (hex) => { const part = (i) => parseInt(hex.slice(i, i + 2), 16) const [r, g, b] = [part(1), part(3), part(5)] return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b) } const ratio = (a, b) => { const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x) return (hi + 0.05) / (lo + 0.05) } // 3. fail the build when a pair used for text is below 4.5:1 const c = tokens.color const pairs = [['text', 'surface'], ['brand-text', 'brand'], ['muted', 'surface']] let failed = 0 for (const [fg, bg] of pairs) { const r = ratio(c[fg], c[bg]) const ok = r >= 4.5 if (!ok) failed++ const label = `${fg} on ${bg}`.padEnd(22) console.log(label, r.toFixed(2), ok ? 'pass' : 'FAIL') } process.exitCode = failed ? 1 : 0
build-tokens.mjs: the contrast formula and the check.
text on surface 14.76 pass brand-text on brand 6.25 pass muted on surface 2.50 FAIL
Output (Node 24), the contrast results
The first two pairs pass. The third pair, a grey for secondary text on white, comes out at 2.50 and fails, so the script sets a non-zero exit code and the build stops. A design change that makes text harder to read never reaches a release.
A formula in your own script is a start, and a browser-based checker is a second opinion. The page below uses the tokens and puts the muted grey on body text. axe-core, the accessibility engine, runs in Chrome against the rendered page.
<!doctype html> <html lang="en"> <title>Tokens in use</title> <link rel="stylesheet" href="tokens.css"> <style> body { background: var(--color-surface); color: var(--color-text); font: 16px sans-serif; padding: var(--space-3) } .note { color: var(--color-muted) } .buy { background: var(--color-brand); color: var(--color-brand-text); border: 0; border-radius: var(--radius-button); padding: var(--space-2) var(--space-3) } </style> <main> <h1>Masala tea</h1> <p class="note">Packed in Mysuru, ships in two days.</p> <button class="buy">Add to cart</button> </main>
page.html: a small page that uses the tokens.
Versioning and monorepos
Every team that uses the library depends on its versions, so a change must say how much it can break. The semantic versioning rules from the requirements chapter apply: MAJOR for an incompatible change, MINOR for added functionality, and PATCH for a fix.
For tokens the mapping needs a policy, since semver leaves it to the project. This script uses one: removing a token breaks anyone using it, so it is major. Adding a token is minor. Changing only a value, as when the muted grey is made darker to pass contrast, is a patch. The policy is ours, and a team might call a large colour change minor or major.
const flat = (t) => Object.fromEntries( Object.entries(t).flatMap(([group, values]) => Object.entries(values).map(([k, v]) => [`${group}-${k}`, v]))) function bump(before, after) { const a = flat(before) const b = flat(after) const removed = Object.keys(a).filter((k) => !(k in b)) const added = Object.keys(b).filter((k) => !(k in a)) const changed = Object.keys(a).filter((k) => k in b && a[k] !== b[k]) const level = removed.length ? 'major' : added.length ? 'minor' : changed.length ? 'patch' : 'none' return { level, removed, added, changed } } const v1 = { color: { text: '#1f2933', muted: '#9aa5b1' } } const v2 = { color: { text: '#1f2933', muted: '#616e7c' } } const v3 = { color: { text: '#1f2933', muted: '#616e7c', danger: '#b42318' } } const v4 = { color: { text: '#1f2933', danger: '#b42318' } } console.log('v1 -> v2', JSON.stringify(bump(v1, v2))) console.log('v2 -> v3', JSON.stringify(bump(v2, v3))) console.log('v3 -> v4', JSON.stringify(bump(v3, v4)))
bump.mjs: the next version from a token diff.
v1 -> v2
{"level":"patch","removed":[],"added":[],"changed":["color-muted"]}
v2 -> v3
{"level":"minor","removed":[],"added":["color-danger"],"changed":[]}
v3 -> v4
{"level":"major","removed":["color-muted"],"added":[],"changed":[]}Output (Node 24)
The darker grey is a patch, the new danger colour is a minor release, and removing the muted token is a major release that every user must read about.
A monorepo keeps the design system, its apps and other shared packages in one repository. Package managers support this directly: npm, pnpm and Yarn have workspaces, which link local packages by name so an app uses the library's current code without publishing it. The benefit is that one change can update the library and every caller in a single review. The cost is that the repository needs tooling to build and test only what a change touched, and clear ownership of each package, or the shared library becomes everyone's and nobody's.
All chapters · Previous: API Styles, Protocols and Data Formats