Context Protocol
The context protocol lets you share data across deeply nested components without threading attributes through every intermediate element. It uses DOM events under the hood, which means it works across shadow DOM boundaries, so a provider at the top of the tree can reach consumers buried many levels deep.
It is a port of Lit's @lit/context, which implements the Web Components Community Group context protocol: createContext, ContextProvider, ContextConsumer, ContextRequestEvent, ContextProviderEvent and ContextRoot take the same arguments and behave the same way, so Lit context code runs unchanged once its import points at @webjsdev/core/context. The @provide and @consume decorators are the one part with no WebJs form, because WebJs TypeScript is erasable and has no decorators: construct the controllers as fields instead, as every example below does.
import { createContext, ContextProvider, ContextConsumer, ContextRoot } from '@webjsdev/core/context'; When to Use Context
Context is the right tool when:
- Theme / dark mode: a setting at the app root that dozens of components read.
- Auth state: the current user object needed by nav bars, comment forms, profile widgets, etc.
- Locale / i18n: language preference that affects every text-rendering component.
- Feature flags: runtime configuration that controls conditional rendering deep in the tree.
Context is not the right tool when:
- Data changes on every render. Use component state instead.
- Only one component needs the data. Pass it as an attribute or property.
- Data is page-level. Use an async page function to fetch it on the server.
Creating a Context
createContext(key) returns the key itself, typed with the value it carries. The KEY is the identity: createContext('theme') in two modules is the same context, and a provider of one answers a consumer of the other. When a context must never collide with another one of the same name, use a Symbol as the key and export it from one module.
// contexts/theme.ts (or .js)
import { createContext } from '@webjsdev/core/context';
export type Theme = 'light' | 'dark' | 'system';
export const themeContext = createContext<Theme>('theme');
// Collision-proof: only code importing this binding can reach it.
export const sessionIdContext = createContext<string>(Symbol('session-id')); The type argument is what flows into provider.value, consumer.value and the callbacks.
Providing a Value
ContextProvider is a reactive controller that provides a value to all descendants. Attach it to any component:
import { WebComponent, html, css } from '@webjsdev/core';
import { ContextProvider } from '@webjsdev/core/context';
import { themeContext } from '#contexts/theme.ts';
class AppShell extends WebComponent {
static shadow = true;
static styles = css`
:host { display: block; }
`;
#theme = new ContextProvider(this, {
context: themeContext,
initialValue: 'light',
});
toggleTheme() {
const next = this.#theme.value === 'light' ? 'dark' : 'light';
this.#theme.setValue(next); // updates all subscribers
}
render() {
return html`
<header>
<button @click=${() => this.toggleTheme()}>
Toggle theme (current: ${this.#theme.value})
</button>
</header>
<main><slot></slot></main>
`;
}
}
AppShell.register('app-shell'); When you call provider.setValue(newValue) (or assign provider.value = newValue), every subscribed consumer is notified and its host component re-renders automatically. Setting the same value again notifies nobody; setValue(value, true) forces the notification, which is how you announce an object you mutated in place.
The provider listens for requests from the moment it is constructed, and it never answers its own host: a component that provides a context and also consumes the same one reads the value from an ancestor. The positional form new ContextProvider(this, themeContext, 'light') is equivalent to the options object.
Consuming a Value
ContextConsumer is a reactive controller that reads the nearest provider's value. Attach it to any descendant component:
import { WebComponent, html, css } from '@webjsdev/core';
import { ContextConsumer } from '@webjsdev/core/context';
import { themeContext } from '#contexts/theme.ts';
class ThemedCard extends WebComponent {
static shadow = true;
static styles = css`
:host { display: block; padding: 16px; border-radius: 8px; }
:host(.dark) { background: #1a1a2e; color: #eee; }
:host(.light) { background: #fff; color: #222; border: 1px solid #ddd; }
`;
#theme = new ContextConsumer(this, {
context: themeContext,
subscribe: true, // re-render when the provider's value changes
});
render() {
// Apply the theme as a class on the host element
this.className = this.#theme.value ?? 'light';
return html`
<h3><slot name="title">Card</slot></h3>
<p><slot></slot></p>
`;
}
}
ThemedCard.register('themed-card'); Subscribe vs One-Shot Mode
The subscribe option controls whether the consumer receives ongoing updates. It defaults to false, as in Lit, so pass subscribe: true whenever the value can change.
subscribe: true
The consumer re-renders whenever the provider calls setValue(). This is what you want for live data like theme, auth state, or locale.
// Consumer re-renders every time the provider's value changes
#theme = new ContextConsumer(this, {
context: themeContext,
subscribe: true,
}); subscribe: false (the default, one-shot)
The consumer reads the provider's value each time its host connects and never updates in between. This is useful for configuration that is set once and never changes, like a base URL:
// Consumer reads the value once and ignores future changes
#apiBase = new ContextConsumer(this, { context: apiBaseContext }); With subscribe: false, calling provider.setValue() does not notify this consumer.
The callback option
Pass callback to run code when a value arrives: once for a one-shot consumer, on every change for a subscribing one. The positional form is new ContextConsumer(this, context, callback, subscribe).
#locale = new ContextConsumer(this, {
context: localeContext,
subscribe: true,
callback: (locale) => document.documentElement.lang = locale,
}); How It Works Under the Hood
The context protocol uses standard DOM events:
- When a consumer connects, it dispatches a
ContextRequestEvent(context, contextTarget, callback, subscribe)that bubbles up through the DOM (including across shadow DOM boundaries, since it is composed).contextTargetis the requesting element. - The nearest ancestor with a matching
ContextProviderintercepts the event and stops it. - If
subscribeis true, the provider stores the callback and calls it, with an unsubscribe function, whenever the value changes. - Otherwise the provider calls back once with the current value.
- When a provider connects it dispatches a
ContextProviderEvent. A provider of the same context further up re-sends its subscribers' requests, so a consumer that now sits below a nearer provider moves to it.
You can dispatch a request yourself for a one-time read:
this.dispatchEvent(new ContextRequestEvent(themeContext, this, (theme) => {
console.log('current theme', theme);
})); This means context works with any DOM tree structure (including components from different libraries) as long as they follow the same context protocol. There is no framework-specific wiring.
Multiple Contexts
A single component can provide or consume multiple contexts:
import { createContext, ContextProvider } from '@webjsdev/core/context';
const themeContext = createContext('theme');
const localeContext = createContext('locale');
const authContext = createContext('auth');
class AppRoot extends WebComponent {
#theme = new ContextProvider(this, {
context: themeContext,
initialValue: 'light',
});
#locale = new ContextProvider(this, {
context: localeContext,
initialValue: 'en',
});
#auth = new ContextProvider(this, {
context: authContext,
initialValue: null,
});
login(user) {
this.#auth.setValue(user);
}
render() {
return html`<slot></slot>`;
}
}
AppRoot.register('app-root'); Nested Providers
Providers can be nested. A consumer resolves to the nearest ancestor provider with a matching context key:
<app-root> <!-- provides theme: 'light' -->
<themed-card> <!-- consumes theme: 'light' -->
</themed-card>
<dark-section> <!-- provides theme: 'dark' (overrides) -->
<themed-card> <!-- consumes theme: 'dark' -->
</themed-card>
</dark-section>
</app-root> This mirrors how CSS custom properties cascade. Inner values shadow outer ones.
Late Providers: ContextRoot
A request that reaches the top of the tree unanswered is lost, which happens when a consumer connects before its provider's element has upgraded (a lazily loaded provider, or a consumer defined first). ContextRoot buffers subscribing requests at the root and replays them when a provider for that context connects. Attach it once, early, before your components load:
import { ContextRoot } from '@webjsdev/core/context';
new ContextRoot().attach(document.body); Only subscribing consumers are replayed, as in Lit; a one-shot request that found no provider stays unanswered.
A provider rendered by a layout needs no ContextRoot. A page boots the components its route renders in nesting order, the outermost layout's first and the page's last, so an element a layout renders is defined before one its page renders, and a page's consumer finds the layout's provider when it first connects. A header control that sets a value the page reads therefore works with each element imported only by the route module that renders it, provided the provider wraps both: put it in the root layout around the header and ${children}.
Server Rendering
Context is a client-side protocol. During server rendering no element is connected, so a consumer's value is undefined in the first paint and arrives when the page hydrates. Render a sensible fallback (this.#theme.value ?? 'light'), or pass first-paint data down as attributes from the page.
Full Example: Auth Context
A complete provider + consumer pair for authentication state:
// contexts/auth.ts
import { createContext } from '@webjsdev/core/context';
export type Auth = { user: { name: string } | null; loading: boolean };
export const authContext = createContext<Auth>(Symbol('auth'));
// components/auth-provider.ts
import { WebComponent, html } from '@webjsdev/core';
import { ContextProvider } from '@webjsdev/core/context';
import { authContext } from '#contexts/auth.ts';
class AuthProvider extends WebComponent {
#auth = new ContextProvider(this, {
context: authContext,
initialValue: { user: null, loading: true },
});
async connectedCallback() {
super.connectedCallback();
try {
const res = await fetch('/api/me');
const user = res.ok ? await res.json() : null;
this.#auth.setValue({ user, loading: false });
} catch {
this.#auth.setValue({ user: null, loading: false });
}
}
render() {
return html`<slot></slot>`;
}
}
AuthProvider.register('auth-provider');
// components/user-menu.ts
import { WebComponent, html } from '@webjsdev/core';
import { ContextConsumer } from '@webjsdev/core/context';
import { authContext } from '#contexts/auth.ts';
class UserMenu extends WebComponent {
#auth = new ContextConsumer(this, {
context: authContext,
subscribe: true,
});
render() {
const { user, loading } = this.#auth.value ?? {};
if (loading) return html`<span>...</span>`;
if (!user) return html`<a href="/login">Sign in</a>`;
return html`<span>Hi, ${user.name}</span>`;
}
}
UserMenu.register('user-menu'); Next Steps
- Reactive Controllers: the general pattern that ContextProvider and ContextConsumer are built on
- Task Controller: async data fetching with loading/error states
- Components: the full component API