completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Designing a component API

Web component API design: data in through properties, news out through events, methods or properties, a custom elements manifest, and safe renames.

By the end, you can
  • 01
    Design what goes in and what comes outTake data in through attributes and properties, send news out as events, and never reach into the page.
  • 02
    Choose a method or a propertyKeep state in a property that HTML can set, and make methods short actions that update it, as <dialog> does.
  • 03
    Document an API and change it safelyDescribe it in a custom elements manifest, deprecate an old name before you remove it, and number versions with semver.

What makes a good web component API?

Ravi's tea kit is growing. Asha uses its timer on the Leaf and Kettle menu page. Now Meena wants it too. She runs a tea stall at the market, and her stall has its own page.

That changes things for Ravi. Two pages now depend on his tags. If he renames one attribute, a page breaks, and he may never hear about it. So before the kit grows, he asks a question. What should the outside of a component look like, so it's easy to use and safe to change?

A web component's API is every part a page can use: its attributes, properties, methods, events, slots, CSS parts, and CSS custom properties. A good one works like a built-in element. Data goes in through attributes and properties. News comes out as events. Actions are methods. And every part is written down, and changed with care.

API is short for application programming interface. Here, it means the parts of your component that other people's code touches. This page uses the kit's timer from the outside:

A page that uses the tea timer from outsidePop out in the code editor (opens in a new tab)HTML
<p>Green tea: <tea-timer seconds="2"></tea-timer></p> <script type="module">  import "./tea-kit/index.js";   const timer = document.querySelector("tea-timer");  console.log("It counts", timer.seconds, "seconds");  timer.addEventListener("tea-timer-done", () => {    console.log("Time to pour");  });</script>
ResultLoading…
  • Line 1 writes the timer with a seconds attribute. That's data going in, from HTML.
  • Line 4 loads every component in the kit.
  • Line 7 reads the seconds property. It prints It counts 2 seconds.
  • Lines 8 to 10 listen for tea-timer-done, the event from lesson 5.3. Two seconds later, the console prints Time to pour.

That's all the page needs. It never sees the countdown, the private #controller field, or how the timer draws Ready. Those stay inside. Ravi can rewrite them any day, and no page will notice.

The tea timer's public side. On the left, two things go in: the seconds attribute, set to 2, and the property timer.seconds, with arrows into the tea-timer card in the middle. On the right, an arrow comes out to the tea-timer-done event. Below the timer, two cards, #controller and the countdown, are private: only the timer uses them.goes inseconds="2"timer.secondsthe component<tea-timer>comes outtea-timer-done#controllerthe countdownprivate: only the timer uses these
A page reaches the timer through three doors: the seconds attribute, the seconds property, and the tea-timer-done event. The countdown and #controller stay inside, so Ravi can change them freely.

The timer uses three kinds of API. Components can have seven:

  • Attributes, like seconds="2", written in HTML. Lessons 5.1 and 5.2 built them.
  • Properties, like timer.seconds, set and read from JavaScript.
  • Methods, like dialog.show(), that do something now.
  • Events, like tea-timer-done, that tell the page what happened.
  • Slots, the places where the page's own content goes. Stage 3, Shadow DOM, templates, and slots, builds them.
  • CSS parts, the inner elements a page may style with ::part().
  • CSS custom properties, like --tea-card-color, that a page sets to theme a component. Lesson 2.3 styled a library's parts and custom properties.
Real-life analogyA café menu and its kitchen

A café's menu is a promise. Customers order what it says, by the names it uses. The kitchen can change its recipes, its pans, and its staff, and nobody out front can tell. But if a dish vanishes from the menu, regulars notice the next morning.

In real life: The menu on the wall
In JavaScript: The public API: attributes, properties, methods, events, slots, parts, and custom properties
In real life: Ordering by name
In JavaScript: A page writing seconds="2" or listening for tea-timer-done
In real life: The recipes in the kitchen
In JavaScript: Private code, like #controller and the countdown
In real life: Taking a dish off the menu
In JavaScript: A breaking change
The main idea

Design a component's outside the way built-in elements do. Data comes in through attributes and properties, and news goes out as events. State lives in properties, and actions are methods. Write every public part down. Then change it only with a deprecation first, and a new major version.

The JavaScript path's Designing good APIs lesson covers API design for functions and classes. This lesson is about what's different for a component. Its API lives in HTML, CSS, and JavaScript at once.

What does properties down, events up mean?

It's a rule about which way things travel between a component and the page around it. Lit's docs call it properties down, events up. The W3C TAG, a group that reviews the web's design, calls it data down, events up.

  • Down: the page, which owns the component, sends data in. It sets attributes and properties.
  • Up: the component sends news out. It dispatches events, as lesson 5.3 showed.

Built-in elements already work this way. A page sets an input's value. When the user types, the input fires an input event. The input never reaches out to change the form around it.

What goes wrong when a component reaches out

Ravi's first cup broke that rule. When you press Add, it finds the <span> in its parent and adds 1 to it. On Asha's cart page, that span is the cart count. Try it, then switch to Meena's page:

Playground: one cup on two pages
A cup that changes its parentPop out in the code editor (opens in a new tab)HTML
<p>  Cart: <span>0</span> teas  <tea-cup tea="Green tea"></tea-cup></p> <script src="tea-cup.js"></script>
ResultLoading…
Try it yourself
It looks right

Press Add. The cart goes from 0 to 1. The cup's parent is Asha's <p>, and its <span> happens to be the cart count.

Lines 2 and 3 change with your choice. The tea-cup.js tab holds the cup: the same file on both pages. Press Add in the result, then Run again to start over.
  • In the tea-cup.js tab, line 5 looks for a <span> in the cup's parent, this.parentElement.
  • Line 6 adds 1 to whatever it finds.
  • On both pages, lines 1 to 4 put the cup in a <p>, next to a <span>.

On Asha's page, Add makes the cart show Cart: 1 teas. On Meena's page, the same click turns the price from 4 into 5. Nothing throws. The cup just changed something that wasn't its business.

The same cup on two pages. On the left, Asha's page: an arrow goes up from the tea-cup to the span next to it, which shows Cart: 1 teas. Marked good: Add counts the cart. On the right, Meena's page: the same arrow goes up to her span, which shows Mint tea, price 5. Marked bad: Add raises the price.Asha's pageCart: 1 teas<tea-cup>Meena's pageMint tea, price 5<tea-cup>Add counts the cartAdd raises the price
The cup adds 1 to the <span> in its parent. On Asha's page, that span is the cart. On Meena's page, it's the price, so one click turns 4 into 5.

The cup assumed every page looks like Asha's. The W3C TAG warns against exactly this: don't make an element depend on a certain parent. web.dev's checklist adds two smaller cases. Don't change the class attribute on your own element, and don't overwrite attributes like tabindex that the page set. Those belong to the page too.

Real-life analogyA delivery rider rings the bell

A delivery rider reads the address on the parcel, rides there, and rings the bell. She doesn't walk in and put the parcel on a shelf. Every house keeps its shelves somewhere else. So she rings, and the people inside decide where it goes.

In real life: The address on the parcel
In JavaScript: The attributes and properties the page sets
In real life: Ringing the bell
In JavaScript: Dispatching tea-add
In real life: Walking in to put things on a shelf
In JavaScript: Changing the parent's <span>
In real life: The next house, with different shelves
In JavaScript: Meena's page

Telling the page instead

Here is Meena's page with the cup from lesson 5.3. The cup only dispatches tea-add. Meena's own script decides what an add means on her page:

Meena's page, with a cup that tells instead of touchingPop out in the code editor (opens in a new tab)HTML
<p>  Mint tea, price <span>4</span>  <tea-cup tea="Mint tea"></tea-cup></p><p>Basket: <output>empty</output></p> <script src="tea-cup.js"></script><script>  const basket = document.querySelector("output");  document.addEventListener("tea-add", (event) => {    basket.textContent = event.detail.tea;  });</script>
ResultLoading…
  • In the tea-cup.js tab, line 7 dispatches tea-add, with the tea in detail. Line 6 makes it bubble and leave shadow roots, as lesson 5.3 advised.
  • Line 5 of the page is Meena's basket.
  • Lines 10 to 12 are her listener. It writes the tea into the basket.

Press Add. The basket shows Mint tea, and the price stays at 4. On Asha's page, the same cup works with the cart listener from lesson 5.3's overview. Each page owns its data. The cup only reports what the user did.

What if two components need to talk, like a cup and a cart? They still don't touch each other. The page listens to one, and sets a property on the other. Lit calls this a mediator. Stage 7, Building components well, comes back to it in a lesson on data flow between components.

Lit adds one more rule. A component that changes one of its own public properties because of the user should dispatch an event. An input fires input when the user types, for the same reason. Lesson 5.3 covered when to dispatch, and when to stay quiet.

Should a web component use a method or a property?

Lesson 2.2 compared the two to a light switch and a doorbell. A property is a switch: it stays where you put it, and anyone can look at it. A method is a doorbell: it does something now. Most components need both. The question is which job gets which.

Built-in elements answer it the same way every time:

  • State is a property. Whether a dialog is open is a fact you can read at any moment. So it's dialog.open.
  • Actions are methods. Moving the cursor into a box happens once, then it's done. So it's input.focus().
  • A method that changes state changes the property too. So the property always tells the truth.

Here are two built-ins doing that last one:

dialog.show() and details.open keep their state in one placePop out in the code editor (opens in a new tab)HTML
<dialog>Green tea is brewing.</dialog><details>  <summary>Brewing guide</summary>  Brew green tea for 3 minutes.</details> <script>  const dialog = document.querySelector("dialog");  const details = document.querySelector("details");   dialog.show();  console.log(dialog.open, dialog.hasAttribute("open"));  dialog.close();  console.log(dialog.open, dialog.hasAttribute("open"));   details.open = true;  console.log(details.hasAttribute("open"), "show" in details);</script>
ResultLoading…
  • Line 11 calls dialog.show(). Line 12 prints true true. The property is true, and the attribute is there.
  • Line 13 calls close(). Line 14 prints false false.
  • Line 16 sets details.open = true. Line 17 prints true false. The attribute appeared, and details has no show() method at all.

The result shows the brewing guide open, because line 16 opened it. The HTML Standard spells out the dialog's side. show() adds the open attribute, and close() removes it. The attribute is the one place the state lives. Here is the same pattern across five built-ins. Read each row across:

State in properties, actions in methods
ElementState you set or read (properties)Actions you call (methods)
<dialog>open, which reflects the open attribute.show(), showModal(), and close(). Each one adds or removes open.
<details>open, which reflects the open attribute.None. Setting open does the whole job.
<input>value and disabled.focus() and select(). They act once, and leave no setting behind.
<form>action and method, which reflect their attributes.reset() and submit(). They act on the whole form at once.
<video>muted and currentTime. You can only read paused.play() and pause(). Playing can take time, so play() gives back a promise.

The W3C TAG's design principles give a test for the hard cases. Reading a property should only read. It shouldn't change anything, or take a long time. If it would, make it a method.

Why state belongs in a property

A property backed by an attribute can be set from more places than a method can:

  • HTML. <details open> works before any script runs. Nothing in HTML can call show().
  • Templates. Lit's docs prefer setting properties to calling methods. Templates in Lit and in frameworks set properties easily.
  • Reading back. Any code can ask menu.open later. A method call leaves nothing to ask.
Real-life analogyA hallway light with two switches

Many homes have a hallway light with two switches, one at each end of the stairs. You can use either one. There's still only one light, and everyone can see whether it's on.

In real life: The switch at the bottom of the stairs
In JavaScript: menu.show()
In real life: The switch at the top
In JavaScript: menu.open = true
In real life: The one light
In JavaScript: The open attribute
In real life: Anyone looking up at the light
In JavaScript: Code that reads menu.open

Ravi's menu follows the same plan. Its show() and hide() only set open. The open setter writes the attribute, as in lesson 5.1. Pick any of the four ways to open it:

Playground: four ways to open the menu
Opening the tea menuPop out in the code editor (opens in a new tab)HTML
<tea-menu></tea-menu> <script src="tea-menu.js"></script><script>  const menu = document.querySelector("tea-menu");  menu.show();  console.log(menu.open, menu.hasAttribute("open"));</script>
ResultLoading…
Try it yourself
Opened by a script

show() sets this.open = true. The setter adds the open attribute, and attributeChangedCallback() draws the menu.

Line 6 changes with your choice, or line 1 for the HTML way. The tea-menu.js tab holds the menu. Every choice prints true true.
  • In the tea-menu.js tab, lines 4 to 10 are the property. Its getter reads the attribute, and its setter writes it with toggleAttribute().
  • Lines 12 to 18 are the two methods. Each one is a single line that sets this.open.
  • Lines 20 to 22 draw the menu whenever the attribute changes.
  • In the page, line 6 is your choice. Line 7 prints true true every time.
Three ways in, one state. On the left, three cards: menu.show(), menu.open = true, and a tea-menu tag written with open in the HTML. Arrows from all three meet at one card in the middle, the open attribute. An arrow leads on to menu.open, which reads true.three ways inmenu.show()menu.open = true<tea-menu open>one stateopen attributemenu.opentrue
show() sets open, the setter writes the attribute, and HTML can write the attribute itself. However you open the menu, menu.open reads true.

Web Awesome's details element does exactly this. Its show() method sets this.open = true, then gives back a promise that waits for the opening animation. Its docs say the open attribute reflects the state, whichever way you open it. Waiting is something only a method can offer. So the method adds what a property can't, and leaves the state in the property.

How do you document a web component's API?

Meena can't read Ravi's mind. She needs a list of what she may use. Semantic versioning, the numbering rule near the end of this lesson, even requires one. A package must declare its public API.

Write down every part a page can touch. For each kind, say this:

  • Attributes and properties: the name, the type, the default, and whether they reflect.
  • Methods: what each one does, what it takes, and what it gives back.
  • Events: the name, when it fires, what it carries, and whether it bubbles or can be canceled.
  • Slots: where the page's content goes. The default slot has no name.
  • CSS parts and custom properties: what each one styles.

Leave everything else out, on purpose. Cory LaViska, who created the Shoelace library, puts it simply. Every part you expose is an API you're promising to support. Private code can change any day. Documented parts can't, without a new major version.

Lesson 2.1 read docs like this from the other side: Web Awesome's tables of attributes, slots, events, and parts. Those tables are made from a file the library ships. The next section opens one. First, here's how authors write the facts down: as comments above the class.

JSDoc tags the analyzer reads

JSDoc is a way of writing comments above code, with tags that start with @. The Custom Elements Manifest Analyzer, a tool from Open Web Components, reads them. Ravi plans the tea card before he builds it in stage 3, so he writes its comment first:

tea-card.js, planned with a JSDoc commentJavaScript
/**
 * A card for one tea on the menu.
 *
 * @tag tea-card
 * @attr {string} tea - The tea's name.
 * @prop {number} price - The price, as a number.
 * @fires {Event} tea-card-select - The user picked this tea.
 * @slot - The tea's description.
 * @csspart title - The tea's name at the top.
 * @cssprop --tea-card-color - The card's background color.
 */
export class TeaCard extends HTMLElement {}
  • Line 4 names the tag.
  • Lines 5 and 6 describe an attribute and a property. The part in braces, like {string}, is the type.
  • Line 7 describes an event.
  • Lines 8 to 10 describe a slot, a CSS part, and a custom property. Line 8 has no name, so it's the default slot.

Run the analyzer on this file, and each tag lands in its own list. Read each row across:

Six JSDoc tags and where they land
JSDoc tagWhat it describesWhere it lands in the manifest
@attrAn attribute the page writes in HTML.It goes in attributes.
@propA property the page sets from JavaScript.It goes in members, as a field.
@firesAn event the component dispatches.It goes in events.
@slotA place for the page's own content. No name means the default slot.It goes in slots.
@csspartAn inner element the page may style with ::part().It goes in cssParts.
@csspropA CSS custom property the component reads.It goes in cssProperties.

The analyzer finds a lot without tags. It reads observedAttributes, class fields, methods, and dispatchEvent() calls by itself. Its docs say slots, CSS parts, and custom properties need JSDoc. The tea timer needs a tag too. It reads seconds without observing it, so only @attr tells the analyzer it's an attribute.

You can try this without installing anything, in the analyzer's online playground. Paste a class with a comment, and watch the manifest change.

What is a custom elements manifest?

A custom elements manifest is one JSON file that describes every custom element in a package. It's usually called custom-elements.json. Its format is shared. People who build tools wrote it together: tools for editors, docs sites, linters, and framework wrappers. Each tool reads the same file, whatever library made the components.

Real-life analogyOne ingredients label, read by everyone

A packet of tea has one printed label: the name, the ingredients, and the brewing time. The shop's shelf tag, the delivery app, and the website all copy from that label. Nobody types the facts in three times.

In real life: The label on the tea packet
In JavaScript: custom-elements.json
In real life: The shelf tag, the delivery app, and the website
In JavaScript: Docs sites, code editors, and framework wrappers
In real life: Printing the label from the recipe
In JavaScript: The analyzer writing the manifest from your code

Ravi writes the timer's manifest by hand, so you can read every line. It's now part of the kit, as tea-kit/custom-elements.json:

custom-elements.json for the tea timerJSON
{
  "schemaVersion": "2.1.0",
  "modules": [
    {
      "kind": "javascript-module",
      "path": "tea-timer.js",
      "declarations": [
        {
          "kind": "class",
          "name": "TeaTimer",
          "customElement": true,
          "tagName": "tea-timer",
          "description": "A brewing timer. It counts down, then shows Ready.",
          "superclass": { "name": "HTMLElement" },
          "attributes": [
            {
              "name": "seconds",
              "fieldName": "seconds",
              "type": { "text": "number" },
              "default": "60",
              "description": "How long to brew, in seconds."
            }
          ],
          "members": [
            {
              "kind": "field",
              "name": "seconds",
              "attribute": "seconds",
              "reflects": true,
              "type": { "text": "number" },
              "default": "60",
              "description": "How long to brew, in seconds."
            }
          ],
          "events": [
            {
              "name": "tea-timer-done",
              "type": { "text": "TeaTimerDoneEvent" },
              "description": "The countdown reached zero. It bubbles and is composed."
            }
          ]
        },
        {
          "kind": "class",
          "name": "TeaTimerDoneEvent",
          "superclass": { "name": "Event" },
          "members": [
            {
              "kind": "field",
              "name": "seconds",
              "type": { "text": "number" },
              "description": "How long the timer counted, in seconds."
            }
          ]
        }
      ],
      "exports": [
        { "kind": "js", "name": "TeaTimer", "declaration": { "name": "TeaTimer" } },
        { "kind": "js", "name": "TeaTimerDoneEvent", "declaration": { "name": "TeaTimerDoneEvent" } },
        { "kind": "custom-element-definition", "name": "tea-timer", "declaration": { "name": "TeaTimer" } }
      ]
    }
  ]
}
  • Line 2 says which version of the format the file uses: 2.1.0.
  • Lines 5 and 6 describe one module, the file tea-timer.js.
  • Lines 9 to 12 say it declares a class, TeaTimer. It's a custom element, with the tag tea-timer.
  • Lines 15 to 23 list the seconds attribute. Its default is the string "60", because attributes are always strings. fieldName links it to the property.
  • Lines 24 to 34 list the seconds property. reflects: true says it and the attribute stay in sync.
  • Lines 35 to 41 list the event, and its type: the TeaTimerDoneEvent class.
  • Lines 43 to 55 describe that class, and its seconds field.
  • Lines 57 to 61 list what the file exports, and which class defines tea-timer.

Every field comes from the format's schema: a file that says which fields are allowed, and which are required. The format lives on GitHub, as TypeScript types and as a JSON Schema, at version 2.1.0. This lesson's test checks the kit's file against that schema. The schema also explains default: it's the attribute's real text, not a description.

Pointing tools to the manifest

A package tells tools where its manifest is with one field in its package.json:

The customElements field in package.jsonJSON
{
  "name": "tea-kit",
  "version": "1.5.0",
  "type": "module",
  "customElements": "custom-elements.json"
}

Line 5 is the field, customElements. The format's README explains why it exists. A tool can find the manifest without downloading the whole package. Lesson 2.1 found this field in Web Awesome's package.

Writing it by hand or with the analyzer

One component is easy to describe by hand. A whole library isn't. Install the analyzer with npm i -D @custom-elements-manifest/analyzer, then run cem analyze. It writes custom-elements.json from your code and its JSDoc. Run it again after each change, and the docs keep up with the code. Still, read what it wrote. A manifest is only as right as the comments it came from.

Burton Smith, who builds a component library, lists what teams make from a manifest: API docs, editor hints, Storybook pages, and wrappers for React and other frameworks. Stage 11, Testing, tooling, and publishing, covers the analyzer, its plugins, and editor support.

What counts as a breaking change in a web component?

A breaking change is a change that can stop a working page from working, when the page itself didn't change. For a component, that covers much more than JavaScript names. Burton Smith points out that web components have more public APIs than framework components. Each one is a promise. These changes break it:

  • Renaming or removing anything public. Attributes, properties, methods, events, slots, CSS parts, and custom properties. Old HTML, scripts, and CSS still use the old name.
  • Changing a default. The kit's label uses 3 minutes when minutes is missing, from lesson 5.2. Change it to 4, and every label without minutes shows a different time.
  • Changing when an event fires. The timer dispatches only after it shows Ready. Dispatch earlier, and a listener reads the old text.
  • Changing an event's shape. Listeners that read detail.tea break if it becomes detail.name.
  • Changing a property's type. Code that adds 1 to minutes breaks if it turns from a number into a string.

Adding things is usually safe. A new optional attribute, a new event, or a new part changes nothing for old pages. Private code is safe too. No page can reach a #private method. Sort these changes:

Breaking or safe?
  • Rename the timer's seconds attribute to duration
  • Rename the card's title CSS part to heading
  • Change the label's default minutes from 3 to 4
  • Change event.detail.tea to event.detail.name
  • Dispatch tea-timer-done before the timer shows Ready
  • Add an optional paused attribute
  • Rename the private #render() method
  • Add tea, and keep type working with a warning
Try it yourself
0 of 8 correct

Sort each change to the tea kit by whether it could break a page that didn't change.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Semantic versioning

Semantic versioning, or semver, is a rule for version numbers. npm's docs recommend it for every package. A version has three numbers, like 1.4.2: major, minor, and patch.

  • The patch number goes up for bug fixes that leave the API alone: 1.4.3.
  • The minor number goes up for new features that break nothing: 1.5.0.
  • The major number goes up for any breaking change: 2.0.0.

So the number is a message. A page on 1.4.2 can take 1.5.0 safely. A jump to 2.0.0 says: read the changelog first. That's why everything in the breaking list needs a major version, even a new default.

How do you rename an attribute or event without breaking pages?

You don't do it in one step. You add the new name, keep the old one working for a while, and remove it later. Marking the old name as on its way out is called deprecating it. Semver says a deprecation goes in a minor version. Its FAQ adds that at least one minor version should carry the deprecation, before a major version removes the old name.

Ravi has two names he regrets. His first cup called its tea attribute type. But on inputs and buttons, type means something else. And its event was add, with no prefix, which lesson 5.3 warned against.

Real-life analogyA drink with a new name on the menu

Leaf and Kettle renames its Morning Mix to Breakfast Blend. For a month, the menu shows the new name with a small note: "was Morning Mix". Regulars who ask for Morning Mix still get their tea. After the month, the old name goes.

In real life: Breakfast Blend, the new name
In JavaScript: The new attribute, tea
In real life: Staff still taking orders for Morning Mix
In JavaScript: The getter falling back to type
In real life: The note under the new name
In JavaScript: The console warning, and deprecated in the manifest
In real life: The month both names work
In JavaScript: The minor versions before 2.0.0
In real life: Dropping the old name
In JavaScript: Removing type in 2.0.0

Keeping an old attribute working

Version 1.5.0 of the cup reads tea, and falls back to type. Try Meena's old page, Asha's updated page, and Meena's page on version 2.0.0:

Playground: an old name, a new name
A cup with a renamed attributePop out in the code editor (opens in a new tab)HTML
<p><tea-cup type="Green tea"></tea-cup></p><p><tea-cup type="Mint tea"></tea-cup></p> <script src="tea-cup.js"></script>
ResultLoading…
Try it yourself
It works, with a warning

Meena still writes type. The getter falls back to it, so both cups work. The console shows one warning, however many cups there are.

Lines 1 and 2 change with the page, and the tea-cup.js tab with the version. Open the console to see the warning.
  • In the tea-cup.js tab on version 1.5.0, line 5 reads tea first. The ?? operator gives back its right side when the left side is null or undefined. So a cup with only type still works.
  • Lines 9 to 12 warn the first time a cup with type connects. The flag on line 1, warned, keeps it to one warning per page.
  • Line 13 draws the cup through the getter.

On version 1.5.0, both pages show Cup: Green tea and Cup: Mint tea. Only Meena's page prints the warning, once. On version 2.0.0, the fallback is gone, and Meena's cups show Cup: null. The warning gave her a whole minor version to switch.

Renaming in three versions. 1.4.0: type works. An arrow marked minor leads to 1.5.0: tea works, and type still works but warns. An arrow marked major leads to 2.0.0: tea only, and type gives null.before1.4.0minordeprecated1.5.0majorremoved2.0.0type workstea workstype works, and warnstea onlytype gives null
Version 1.5.0 adds tea and keeps type working, with a warning. That's a minor version. Version 2.0.0 removes type, so old pages show Cup: null. That's a major version.

A console warning only reaches people who open the console. So mark the old name in the docs too. The manifest has a field for it: every attribute, event, slot, part, and custom property can have deprecated, set to true or to a reason. The analyzer fills it in from a @deprecated tag in a property's comment.

Keeping an old event working

For an event, dispatch both names, the new one first:

A cup that dispatches its new event name and its old onePop out in the code editor (opens in a new tab)HTML
<tea-cup tea="Green tea"></tea-cup> <script>  class TeaCup extends HTMLElement {    connectedCallback() {      this.innerHTML = "<button>Add</button>";      this.addEventListener("click", () => {        const tea = this.getAttribute("tea");        const options = { bubbles: true, composed: true, detail: { tea } };        this.dispatchEvent(new CustomEvent("tea-add", options));        // Deprecated in 1.5.0. Remove in 2.0.0.        this.dispatchEvent(new CustomEvent("add", options));      });    }  }  customElements.define("tea-cup", TeaCup);   document.addEventListener("add", (event) => console.log("Meena's old listener:", event.detail.tea));  document.addEventListener("tea-add", (event) => console.log("Asha's new listener:", event.detail.tea));</script>
ResultLoading…
  • Line 10 dispatches the new tea-add.
  • Line 12 dispatches the old add, with the same options. The comment on line 11 says when it goes.
  • Lines 18 and 19 stand for two pages' listeners: Meena's old one, and Asha's new one.

Press Add. The console prints Asha's new listener: Green tea, then Meena's old listener: Green tea. Both pages keep working until 2.0.0.

Parts, slots, and custom properties have moves of their own. An element can carry two part names, so old and new CSS both match. Web Awesome's button does this. Its inner button has part="base button", and its docs comment marks base as deprecated. Burton Smith shows the same idea for slots and custom properties. The JavaScript path's lesson on retiring an old API covers the rest: warning once, and writing the changelog.

Adding API docs to the tea kit

Ravi's kit now ships its first docs. Two files changed in the latest kit:

  • tea-kit/tea-timer.js got JSDoc comments. Its code is the same as in lesson 5.3.
  • tea-kit/custom-elements.json is new. It's the manifest from the section above.

A manifest is data, so code can read it. This page does a small version of what a docs tool does. It loads the manifest, and checks the timer's documented default against the real one:

Checking the timer's docs against the timerPop out in the code editor (opens in a new tab)HTML
<p>Green tea: <tea-timer seconds="2"></tea-timer></p> <script type="module">  import "./tea-kit/index.js";   async function checkDocs() {    const response = await fetch("./tea-kit/custom-elements.json");    const manifest = await response.json();    const docs = manifest.modules[0].declarations[0];    const fresh = document.createElement(docs.tagName);    for (const attribute of docs.attributes) {      const real = String(fresh[attribute.fieldName]);      console.log(attribute.name, attribute.default === real ? "matches" : "differs", real);    }    for (const event of docs.events) {      document.addEventListener(event.name, () => console.log(event.name, "arrived"));    }  }   checkDocs();</script>
ResultLoading…
  • Lines 7 and 8 load the manifest with fetch(), and read it as JSON.
  • Line 9 picks the first declaration, TeaTimer.
  • Line 10 makes a fresh timer, with no attributes.
  • Lines 11 to 14 compare each attribute's documented default with what the fresh timer's property really gives back. Line 13 prints seconds matches 60.
  • Lines 15 to 17 listen for every documented event. After 2 seconds, line 16 prints tea-timer-done arrived.

Now open the tea-kit/tea-timer.js tab. Lines 14 to 20 are the class's JSDoc comment, with @tag on line 17, @attr on line 18, and @fires on line 19. Line 24 describes the property, and line 9 the event's field.

Why it matters: if Ravi ever changes the default in the code but not in the docs, line 13 prints differs. This lesson's test runs the same kind of check on every field, so the kit's docs can't quietly go wrong.

An API checklist for the kit

Ravi keeps this list next to the kit, and checks each new component against it:

  • Simple data is an attribute with a matching property (5.1, 5.2).
  • Rich data, like arrays and objects, is a property only.
  • A property set before the upgrade still works (4.2).
  • State is a property. Actions are methods that update it.
  • News goes out as prefixed events that bubble and are composed (5.3).
  • The component never changes its parent, the page, or the page's own attributes on it.
  • Every public part is in the manifest.
  • A rename goes through a deprecation in a minor version, then a removal in a major one.

web.dev's Custom element best practices has a longer checklist, with the reason for each item. Its shadow DOM items wait for stage 3 and stage 4.

Common mix-ups

  • "Only the JavaScript properties are a component's API." No. Attributes, events, slots, CSS parts, and custom properties are API too. Renaming any of them breaks someone.
  • "A component should update the page itself when something happens." No. It dispatches an event, and the page decides. Then the same component works on any page.
  • "A method is the best way to change state." No. Keep state in a property backed by an attribute, so HTML and templates can set it. A method can wrap it.
  • "If show() sets the state, the property can't." No. Both lead to the same attribute, as dialog.show() and dialog.open = true do.
  • "Changing a default isn't breaking, because no name changed." No. Every page that relied on the old default now shows something else.
  • "Deprecating means deleting." No. A deprecated name still works. It goes later, in a major version.
  • "Browsers read custom-elements.json." No. Tools read it: editors, docs sites, and linters. The browser never loads it.
  • "Only Lit components can have a manifest." No. The format is shared. You can write one by hand, or have the analyzer write it from plain JavaScript.

Practice exercises

Answer first, then use the hints. The results run live, so you can check yourself.

Exercise 1 · Warm-upA dialog opened and closed

What does line 4 print?

Starter codePop out in the code editor (opens in a new tab)JavaScript
const dialog = document.createElement("dialog");
dialog.show();
dialog.close();
console.log(dialog.open, dialog.getAttribute("open"));

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upA new default on an old page

    Version 1 of this label used 3 minutes when minutes was missing. A later version changed line 6 to 4. Meena's page didn't change. What does it show now?

    <tea-label name="Green tea"></tea-label>
    
    <script>
      class TeaLabel extends HTMLElement {
        get minutes() {
          return Number(this.getAttribute("minutes") ?? 4);
        }
    
        connectedCallback() {
          const name = this.getAttribute("name");
          this.textContent = `${name}: brew for ${this.minutes} minutes`;
        }
      }
      customElements.define("tea-label", TeaLabel);
    </script>

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeA cup that calls the page

      Press Add: the basket stays empty, and the console shows an error. Make the cup tell the page instead. What does the basket show after one click?

      <p>Basket: <output>empty</output></p><tea-cup tea="Mint tea"></tea-cup> <script>  class TeaCup extends HTMLElement {    connectedCallback() {      const tea = this.getAttribute("tea");      this.innerHTML = `<button>Add ${tea}</button>`;      this.addEventListener("click", () => {        updateCart(tea);      });    }  }  customElements.define("tea-cup", TeaCup);   document.addEventListener("tea-add", (event) => {    document.querySelector("output").textContent = event.detail.tea;  });</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeA menu that says closed but isn't

        The menu shows Menu closed, but line 17 prints true. Fix hide() so the property agrees. What does the console print then?

        <tea-menu open></tea-menu> <script>  class TeaMenu extends HTMLElement {    get open() {      return this.hasAttribute("open");    }     hide() {      this.textContent = "Menu closed";    }  }  customElements.define("tea-menu", TeaMenu);   const menu = document.querySelector("tea-menu");  menu.hide();  console.log(menu.open);</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeKeep an old property working

          Meena's old code sets cup.type, the property's old name. Nothing happens, and the cup still shows Cup: Green tea. Keep type working, with a warning. What does the cup show then?

          <tea-cup tea="Green tea"></tea-cup> <script>  class TeaCup extends HTMLElement {    static observedAttributes = ["tea"];     get tea() {      return this.getAttribute("tea");    }     set tea(value) {      this.setAttribute("tea", value);    }     attributeChangedCallback() {      this.textContent = `Cup: ${this.tea}`;    }  }  customElements.define("tea-cup", TeaCup);   // Meena's old code still sets the old property.  document.querySelector("tea-cup").type = "Mint tea";</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeWeb Awesome's deprecated part

            Start from Web Awesome's package.json, follow its customElements field to the manifest, and find wa-button's base part. Which part does it tell you to use instead?

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask which way the data goes, where the state lives, and who could break.

              The component API design quiz · 8 questionsScore: first tries count
              1. Question 1 of 8Asha's page wants the cup to show Mint tea. How should it tell the cup?

                Choose an answer to see the explanation.

              2. Question 2 of 8The cup that adds 1 to a <span> in its parent sits on Meena's price list. What happens when she presses Add?

                Choose an answer to see the explanation.

              3. Question 3 of 8What does this details snippet print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const details = document.createElement("details");
                details.open = true;
                console.log(details.hasAttribute("open"), "show" in details);

                Choose an answer to see the explanation.

              4. Question 4 of 8Why should a component's open state be a property, not only a show() method?

                Choose an answer to see the explanation.

              5. Question 5 of 8Which change to the tea timer needs a new major version?

                Choose an answer to see the explanation.

              6. Question 6 of 8The cup is at version 1.4.2. Ravi adds tea and keeps type working, with a warning. What's the next version?

                Choose an answer to see the explanation.

              7. Question 7 of 8What does the customElements field in a package.json do?

                Choose an answer to see the explanation.

              8. Question 8 of 8Which JSDoc tag tells the analyzer about an event?

                Choose an answer to see the explanation.

              Key takeaways

              • A component's API is every part a page can touch: attributes, properties, methods, events, slots, CSS parts, and custom properties.
              • Properties down, events up. The page sends data in, and the component sends news out.
              • A component never reaches into its parent or the page. Then the same component works on every page.
              • State lives in a property backed by an attribute. Methods are actions that update it, like dialog.show().
              • A custom elements manifest describes every public part in one JSON file that tools read. A package points to it with customElements in its package.json.
              • JSDoc tags like @attr, @prop, @fires, @slot, @csspart, and @cssprop let the analyzer write the manifest for you.
              • Renames, removals, new defaults, and changes to an event's timing or shape are breaking. They need a major version.
              • Deprecate first: keep the old name working, warn, and mark it in the docs, in a minor version. Remove it in the next major one.

              Remember the one-liner.
              Data in through properties, news out through events, state in properties, actions in methods, every part written down, and no rename without a deprecation first.

              Sources

              The facts on this page come from these standards, docs, source files, and posts:

              Coming next: Working with children. Read and react to the elements a user puts inside your component, including ones added later.

              CompleteFrontend Clear concepts. Working examples.