Skip to content

    Frontend System Design

    Plugin and Extension Architectures

    Design a front end others can extend: manifests as data, lazy activation, capability-limited APIs, hooks, failure isolation, and why in-process is no sandbox.

    By Published 13 min read

    • frontend-system-design
    • plugins
    • extensions
    • sandboxing
    Share

    Standard lessonadvancedTypeScript labFrontend System Design

    Before this: Command, Strategy, Adapter and Facade

    What you'll learn: By the end of this lesson you will be able to describe the three decisions behind any plugin system (the contract, the lifecycle, the trust boundary), read a manifest as data, explain lazy activation, hand a plugin only the capabilities it asked for, isolate a failing plugin, order hooks, and say precisely why a capability object in the same JavaScript realm is not a sandbox and what the stronger options cost.

    Picture a food hall. The landlord provides stalls with standard power and water. Each vendor signs a lease that lists what they will use. The landlord lights a stall only when customers ask for it, and one vendor's kitchen fire must not close the hall. The hard question is the back office: you can hand vendors a key to the till, or a window to serve through. A plugin architecture is that lease, that opening schedule and that window.

    The running example is the product page of the grocery marketplace front end used in this course. The team wants other teams to add a price label, an "export my note" command and a currency display without editing the page's core code.

    The core idea

    1. The contract is what the host promises. Named extension points (commands, hooks), a versioned API, and data the host can read without running the plugin.
    2. The lifecycle is install, activate, deactivate. Work happens only when something needs it, and a plugin releases what it registered when it goes.
    3. The trust boundary is a separate decision. Giving a plugin a narrow API is different from stopping it reaching everything else. Most plugin systems blur the two.

    Third-party vendor scripts and iframes are covered in Third-Party Scripts and Iframe Sandboxing; this lesson is about the architecture of the host you design, which may run first-party code, partner code or both. The patterns underneath (command, facade, observer) have their own lessons in this module.

    The contract: a manifest the host can read

    VS Code's extension anatomy page says each extension must have a package.json as its Extension Manifest, with VS Code-specific fields such as activationEvents and contributes. It calls contribution points "static declarations that you make in the package.json Extension Manifest to extend VS Code". Static is the important word: the host can list a plugin's commands without running any of its code.

    The lab (examples/frontend/labs/plugin-host-model) has a manifest of the same kind: an id, a version, the host API version it was written for, a closed list of permissions, the commands it declares, its activation events and its dependencies. parseManifest validates it as untrusted data and returns every problem at once.

    Expected output, captured from a real run (the first scenario of the lab demo):

    === 1. manifests are checked as data, before any plugin code runs
      acme.export            accepted
      a broken manifest      rejected with:
        - id must be lowercase dotted words such as acme.promo
        - version must look like 1.2.3
        - apiVersion 2 is not the host's 1
        - unknown permission camera
        - onCommand:other names a command this plugin does not declare

    The permission list and the rules are this lab's own design, not any product's.

    Figure 1. A host and its plugins

    A plugin hostProduct page to Plugin host (hooks, commands); Manifests to Plugin host (declared up front); Plugin host to Context (build per plugin); Context to Plugin A; Context to Plugin BProduct page: core UIProduct pagecore UIPlugin host: registry, lifecycle, guardPlugin hostregistry,lifecycle, guardContext: granted capabilities onlyContextgrantedcapabilities onlyPlugin A: hook: price labelPlugin Ahook: price labelPlugin B: command: exportPlugin Bcommand: exportManifests: read as dataManifestsread as datahooks, commandsdeclared up frontbuild per plugin

    How to read this: the page calls the host, never a plugin directly. The host builds a context for each plugin from its manifest; the plugin sees only what the context holds.

    The lifecycle: activate when needed

    VS Code's activation events reference describes the activationEvents field of the manifest as JSON declarations; onCommand activates interested extensions whenever the command is invoked, onLanguage when a file of a language is opened, and * whenever VS Code starts up. The page asks extension authors to use the start-up event only when no other event works. The extension anatomy page says activate runs when a registered activation event happens, and deactivate gives the extension a chance to clean up.

    The lab follows that shape. Installing runs no plugin code. startup() activates the plugins with an onStartup event; executeCommand activates a plugin the first time one of its declared commands is run, and not again.

    Figure 2. The lifecycle of one plugin

    stateDiagram-v2 accTitle: Plugin lifecycle in the lab host accDescr: A plugin starts installed. An activation event or a dependency's activation makes it active. Deactivation returns it to installed and releases what it registered. A thrown activation, a dependency problem or too many consecutive failures make it disabled, after which the host does not run it again. [*] --> Installed Installed --> Active: activation event Active --> Installed: deactivate, release Installed --> Disabled: dependency problem Active --> Disabled: activate threw, or too many failures Disabled --> [*]

    How to read this: only Active plugins have anything registered. Leaving Active, by either arrow, releases every command and hook the plugin added.

    Illustration 1: the minimal example

    Expected output, captured from a real run (second scenario of the lab demo, first lines):

    === 2. lazy activation: only startup plugins run at start; the rest wait for their event
      declared commands      acme.export.copy, acme.note.append  (known without running any plugin)
      registered commands    none
      after startup          promo=active export=installed note=installed
      first run of the command: 2 x milk | fetched https://rates.example/today
      after the command      export=active  registered: acme.export.copy

    Both commands are known from the manifests before anything runs. After start-up only the label plugin is active; the export plugin becomes active on its first command.

    Capabilities: hand over only what was asked for

    Chrome's extension documentation says an extension declares its intent in the manifest's permissions fields, with permissions taking known strings, host_permissions taking match patterns for hosts, and optional_permissions granted by the user at runtime instead of at install time. It says permissions help limit damage if an extension is compromised, and that permissions with warnings are shown to users before install.

    The lab's context works the same way. It builds a document object holding only the granted methods (read for document.read, write for document.write) and a network object only for network.fetch. A plugin can register only commands its manifest declared.

    Illustration 2: the realistic example

    Expected output, captured from a real run (third scenario of the lab demo):

    === 3. capabilities: the context holds only what the manifest asked for
      acme.export (read, fetch)   2 x milk | fetched https://rates.example/today
      acme.note (read only)       write is undefined: this plugin was not granted document.write
      document text afterwards    "2 x milk"

    The note plugin asked for read access only, so write is simply absent from its context. This is the object-capability style: a plugin cannot use what it was not given a reference to.

    Hooks, ordering and failure isolation

    A hook is a named extension point where several plugins transform a value in turn. The lab sorts handlers by priority (highest first), then by install order, and passes each handler's output to the next. Every call into plugin code is wrapped: a throwing handler is skipped, the failure is counted, and after three consecutive failures the plugin is disabled and its commands and hooks removed. A success resets the count.

    VS Code's extension host page states the goal this serves: the Extension Host prevents extensions from impacting start-up, slowing UI operations or modifying the UI, and "misbehaving extensions should not impact the user experience". That page does not describe the mechanism, and the lab's guard is a much smaller thing: it catches exceptions.

    Expected output, captured from a real run (fourth scenario of the lab demo):

    === 4. hooks run in priority order, and a failing plugin is isolated, then disabled
      render 1: USD 4.20 (member price)
      render 2: USD 4.20 (member price)
      render 3: USD 4.20 (member price)
      render 4: USD 4.20 (member price)
      acme.flaky is disabled (3 consecutive failures)
      host log since start:
        failure acme.flaky in hook price.display: cannot format price (1 of 3)
        failure acme.flaky in hook price.display: cannot format price (2 of 3)
        failure acme.flaky in hook price.display: cannot format price (3 of 3)
        disable acme.flaky: 3 consecutive failures

    Three plugins hook the price: a currency plugin (priority 10) runs first, the failing plugin (5) throws every time, and the label plugin (0) runs last. Every render still shows USD 4.20 (member price). What the guard cannot do is stop a plugin that never returns: a synchronous infinite loop in the same thread blocks everything. Figma's write-up of its plugin system accepts this for plugin code running on the main thread: plugins can hang, which they allow because plugins run only on explicit user action.

    Plugins may also depend on each other. The host activates dependencies first, and disables a plugin whose dependency is missing, disabled or part of a cycle.

    Trust: a capability object is not a sandbox

    Everything above limits what a well-behaved plugin is handed. It does not limit what plugin code can reach. In the lab, all plugins run in the host's own JavaScript realm, so a plugin that ignores its context can read any global the host left lying around.

    Illustration 3: a failure and an edge

    Expected output, captured from a real run (seventh scenario of the lab demo):

    === 7. in one realm, the context is not a sandbox; a copy boundary changes what crosses
      plugin with no permissions reads a host global: demo-token-not-a-secret
      direct call mutates the host's object:   {"sku":"milk","prices":[4.2,0]}
      through a copy boundary it does not:     {"sku":"milk","prices":[4.2]}
      a function cannot cross:                 DataCloneError

    The "token" is a harmless string the demo plants. The plugin had no permissions and still read it. The rest of the output shows what a copy boundary changes: when arguments and results are structured-cloned, a handler's mutation of its argument does not reach the host's object, and a function cannot cross. MDN's guide to web workers describes both halves of that model: a worker runs in another global context, cannot manipulate the page's DOM or objects, and data passed between the page and a worker is copied, not shared. The lab's crossBoundary models only the copy behaviour; it isolates nothing.

    Choosing how much isolation

    Level What it gives What it costs
    Same realm, capability context (the lab) Simple, fast, synchronous API No protection from a hostile plugin; hangs block the page
    Sandboxed iframe A separate browsing context; restrictions lifted token by token Asynchronous messages; a separate document per plugin
    Web Worker Another global context, no DOM Asynchronous, copied data; no DOM access for the plugin
    Realm or VM in the page Synchronous API to a restricted environment Depends on the implementation being correct

    MDN's sandbox attribute description says an empty value applies all restrictions and that tokens lift particular ones. It also says that when the embedded document has the same origin as the embedding page, combining allow-scripts and allow-same-origin is strongly discouraged, because the embedded document can then remove the sandbox attribute, making it no more secure than not using it. The third-party scripts lesson above works through that case.

    Figma's write-up of its plugin system is the best-documented trade-off story among the sources used here. It says message passing is asynchronous, which forced async and await on plugin authors, and that copying the document was too costly: it reports 14 seconds to serialize the document and send it to a plugin. It chose Realms, which keeps the browser's JIT and "still works as a whitelist rather than a blacklist, which keeps its implementation small and auditable"; browser APIs such as UI and network are reached through a separate iframe. It also states the risk, "Realms could have an undiscovered vulnerability", and its update note says Figma later moved to a JavaScript VM written in C and compiled to WebAssembly after a Realms vulnerability was disclosed. The authors add that for platforms with other needs, isolating code in iframes may be sufficient, "and simple is always good".

    The TC39 ShadowRealm proposal describes a distinct global environment with its own global object, intrinsics and built-ins, and was at Stage 2.7 when read; its page does not address security, so treat it as an isolation of globals and not a promise about hostile code.

    Figure 3. Picking a trust level

    flowchart TD accTitle: Choosing a plugin trust level accDescr: If plugins are written by your own team and reviewed, a capability context in the same realm may be enough. If they come from partners or the public, run them in a separate context, a sandboxed iframe or a worker, and talk to them with messages. A{"Who writes the plugins?"} -->|"your team, reviewed"| B["Same realm, capability context, strict guard"] A -->|"partners or the public"| C{"Need a synchronous API?"} C -->|no| D["Sandboxed iframe or worker, messages only"] C -->|yes| E["Restricted realm or VM, audited, with a fallback plan"]

    How to read this: the question is not how clever the plugin API is but who can put code on the page. Code you do not control belongs behind a boundary the browser enforces.

    API versions

    Plugins outlive host releases. The lab refuses a manifest whose apiVersion differs from the host's, which is a deliberately blunt rule. A real host needs a policy for how long an old API version keeps working; the design-system lesson on governance and versioning discusses deprecation for shared components, and the same discipline applies.

    Trade-offs

    Choice Gain Cost
    Static manifests The host lists commands and permissions without running code A new capability means a manifest change and a review
    Lazy activation Page start is not slowed by idle plugins First use pays the start-up cost; activation events need care
    Narrow context Least privilege; easy to audit More API to design and version
    Strike limit A broken plugin stops hurting everyone A failure that depends on the input can disable a healthy plugin
    Strong isolation Defends against hostile code Asynchronous API, copying, more moving parts

    Build it

    The lab is examples/frontend/labs/plugin-host-model: a pure model. src/manifest.ts validates manifests, src/host.ts holds the registry, lifecycle, context, hooks and guard, src/boundary.ts the copy model, and src/samples.ts six small plugins.

    cd examples/frontend/labs/plugin-host-model
    ../../node_modules/.bin/vitest run   # 22 tests
    node src/demo.ts                     # the output shown above

    Verified. The tests passed and every captured block above is a verbatim excerpt of examples/frontend/golden/plugin-host-model.txt. It is a model: one realm, no real isolation, no network or timers, and a permission list invented for the lab.

    In practice: letting other teams extend the product page

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    Three teams want to change the product page: a price label, a currency display, a note export. Today each edits the page's component directly, and releases collide. A fourth request comes from a partner who wants to add a badge.

    Starting architecture

    Figure 4. Starting point: everyone edits the page

    Starting architecture: teams edit the page directlyTeam A to Product page (edit); Team B to Product page (edit); Team C to Product page (edit)Team A: price labelTeam Aprice labelTeam B: currencyTeam BcurrencyTeam C: exportTeam CexportProduct page: one component, many editsProduct pageone component,many editsediteditedit

    How to read this: the warning box is a single file that every team changes, so any release can break another team's feature.

    Options considered

    Option What it fixes What it costs Risk
    Keep editing the page Nothing new Nothing new Collisions continue
    In-realm plugin host for first-party teams Separate releases, narrow API A host to build and version A hostile plugin is not contained
    Host plus a sandboxed iframe for partners Containment for outside code Asynchronous API for partners More to build

    The decision

    Field Decision record
    Context Three reviewed first-party teams now; one outside partner asking.
    Decision An in-realm host with manifests, lazy activation, a capability context and a strike limit for first-party plugins. The partner badge goes in a sandboxed iframe, not in the host.
    Consequences, good Teams ship separately; the host lists what each plugin can touch.
    Consequences, bad The host's API becomes a product with versions.
    Revisit when Another outside party needs more than a badge.

    Rollout and verification

    1. Test the contract: manifest validation, activation, deactivation and release, as the lab does.
    2. Migrate one plugin at a time behind a flag and compare the rendered price strings against the old page.
    3. Alert on disablement: a disabled plugin is an incident, not a log line.
    4. Review manifests like code: a new permission needs a reason.

    The 2 a.m. failure

    The member-price label vanishes for some products. Its hook throws when a price is missing (out-of-stock items), three such renders in a row disable the plugin, and the label disappears for everyone until the page reloads. The strike limit worked as designed and still hid a healthy plugin.

    First three checks: (1) the host log for failure lines and the hook input; (2) whether the failures share an input shape; (3) whether disablement raised an alert. Mitigation: the plugin handles a missing price; the host passes a frozen, validated value. Follow-up: a test that feeds every hook the awkward values (missing, zero, huge) and a rule that disabling needs a per-input failure rate, not three in a row.

    Architect's notes

    • Design the extension points before the first plugin. Every hook is a promise you keep across versions.
    • Prefer declarations to code. What the host can know without running a plugin, it can show, check and disable.
    • Treat "disabled" as an event. Someone has to hear about it.
    • Do not call a capability object a sandbox. Say what it limits and what it does not.

    Common mistakes

    • Exposing the whole application object to plugins.
    • Activating everything at start-up.
    • Letting plugins register anything they like, with no declaration to review.
    • Counting failures with no context, so input-dependent bugs disable healthy plugins.
    • Running partner code in the same realm because it was convenient.

    Key takeaways

    • A plugin system is a contract, a lifecycle and a trust boundary; decide them separately.
    • Manifests are data: the host can read, list and check them without running code.
    • Activate lazily, release on deactivate, and keep the API narrow.
    • Guard every call into plugin code, and make disablement visible.
    • A capability object limits what is handed over, not what can be reached; hostile code needs a boundary the browser enforces.

    Practice exercises

    Exercise 1: Starter (30 min). Add a storage permission to the lab with a per-plugin key space, and a test that one plugin cannot read another's keys through its context.

    Exercise 2: Intermediate (2 hours). Make the strike limit count failures per distinct input and describe what it protects against and what it lets through.

    Exercise 3: Advanced (half day). Move one hook behind a message boundary (a function over cloned data only) and list what the plugin author loses.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments