· ·

Alert Banner Builder: A Custom Field for Site Alerts

Alex Lentz

Title card: Alert Banner Builder: A Custom Field for Site Alerts. Marketplace post on Sitecore Saga.

Every site I’ve ever worked on needs an alert banner at some point. Office closures, a maintenance window, a product recall, the weather. And every time, the content model ends up looking the same: a rich text field for the message, a droplist for severity, a checkbox for “dismissible”, maybe a General Link for the button, and a page of instructions so authors know which combination does what. It works, but authors hate it, and they never get to see what the thing will look like until they preview the page.

So last year I built a Marketplace app for it. Alert Banner Builder is a custom field for the SitecoreAI Page builder. Authors get a visual editor with a live preview, and the field saves clean JSON that the head app renders however the design system wants. I’ve had it on GitHub for a while, but it needed some love before I’d tell people to go use it. This week it got that love, so let’s talk about it.

Alert Banner Builder: configuration panel on the left with message, type, display behavior and colors, live preview of a warning banner on the right.
Configuration on the left, live preview on the right.

What It Does

Authors pick the message, the type (info, warning, error, success), how it behaves (dismissible, persistent, or auto-hide after a few seconds), an icon, colors, an optional call to action, where it sits on the page and how it animates in. Picking a type sets sensible default colors and an icon, and they can override from there. When they hit Save & close, the field gets a JSON value like this:

{
"message": "Scheduled maintenance Saturday 2-4 AM CT.",
"type": "warning",
"displayOption": "dismissible",
"dismissible": true,
"icon": "alert-outline",
"backgroundColor": "#FFF6E7",
"textColor": "#7A2F00",
"cta": { "text": "Details", "url": "/status", "style": "primary" },
"position": "top",
"animation": "slide-down"
}

That’s the whole point of a custom field. The CMS stores data, not markup. Your front end decides what a warning banner looks like.

How Custom Fields Work

If you haven’t built one yet, a Page builder custom field is just a web app that Sitecore loads in an iframe when the author opens the field. The Marketplace SDK handles the handshake with the host, and for a custom field you really only need three calls:

  • client.getValue() – read whatever is in the field right now
  • client.setValue(value, true) – write it back. The second argument tells the host to reload the canvas so the page preview updates
  • client.closeApp() – close the dialog

Wiring it into a template is quick. Add a field, set the type to Marketplace Types > Plugin, and put your Marketplace app ID in the Source. Reload the Page builder and the field shows up. The Sitecore docs walk through registering the app and enabling the custom field extension point in the Cloud Portal, links are at the bottom.

Connecting to the Host Without a Blank Screen

The original version of the app had the same provider a lot of us copied from the early samples. It initialized the SDK, queried application.context, and rendered null until both came back. If anything went sideways, the author got a white box. Not great.

The refreshed provider caches the client once per tab (React Strict Mode runs effects twice in dev, and you don’t want two handshakes), retries a few times, and shows a real error with a Try again button when it can’t connect. Here’s the core of it:

let clientPromise: Promise<ClientSDK> | null = null;
function getClient(): Promise<ClientSDK> {
if (!clientPromise) {
clientPromise = ClientSDK.init({
target: window.parent,
modules: [XMC],
}).catch((error: unknown) => {
// Let the next attempt try again instead of caching the failure
clientPromise = null;
throw error;
});
}
return clientPromise;
}
async function connectWithRetry(): Promise<Connection> {
// Opened directly in a browser tab instead of inside Sitecore
if (window.parent === window) {
throw new Error("This app has to run inside SitecoreAI.");
}
let lastError: unknown;
for (let attempt = 1; attempt <= RETRY_ATTEMPTS; attempt++) {
try {
const client = await getClient();
const { data } = await client.query("application.context");
if (!data) throw new Error("The host returned an empty application context.");
return { client, appContext: data };
} catch (err) {
lastError = err;
if (attempt < RETRY_ATTEMPTS) {
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
}
}
}
throw lastError instanceof Error ? lastError : new Error("Unknown error connecting to SitecoreAI.");
}

The window.parent === window check is a small thing, but it saves a lot of confusion. Somebody always opens the app URL directly in a browser tab to “see if it’s working”, and now they get a message that tells them why it isn’t instead of a spinner that never stops.

The Bug That Was Hiding in Plain Sight

Here’s a fun one I found during the cleanup. The display behavior dropdown had three options, but you could only ever save one of them. Pick Timed, and it snapped right back to Dismissible. The handler looked totally reasonable:

// Before
onValueChange={(v) => {
updateConfig("displayOption", v as DisplayOption)
updateConfig("dismissible", v === "dismissible")
}}
// where updateConfig is
const updateConfig = (key, value) => onChange({ ...config, [key]: value })

Both calls spread the same config from that render. The first one sets displayOption, the second one sets dismissible on the old object, and the parent ends up with the second result. Long story short, the second call quietly undid the first. One onChange with both properties fixes it:

onValueChange={(v) => {
onChange({
...config,
displayOption: v as DisplayOption,
dismissible: v === "dismissible",
})
}}

Classic stale closure. If you’ve got a form component with a updateField(key, value) helper anywhere in your codebase, go look for places that call it twice in a row. I’ll wait.

While I was in there I also fixed a default icon name that didn’t exist in the icon map (so new banners showed no icon until you picked one), and added validation on the CTA URL. Only relative paths, http(s), mailto: and tel: get saved, with an inline error otherwise. The rendering side checks again, because you should never trust a field value just because your own editor wrote it.

Rendering It in Your Head App

The repo now ships a drop-in Content SDK component in examples/content-sdk/AlertBanner.tsx. It parses the field defensively (authors can clear a field, and an empty or broken value should mean “no banner”, not a crashed page), re-checks colors and the CTA URL, handles dismiss and the timed auto-hide, and remembers a dismissal for the session. The important bits:

const HEX = /^#[0-9a-f]{6}$/i;
const SAFE_URL = /^(https?:\/\/|\/|#|mailto:|tel:)/i;
function parseConfig(raw: string | undefined): AlertBannerConfig | null {
if (!raw?.trim()) return null;
try {
const config = JSON.parse(raw) as AlertBannerConfig;
return config.message?.trim() ? config : null;
} catch {
return null;
}
}
export const Default = ({ fields, params }: AlertBannerProps) => {
const config = useMemo(() => parseConfig(fields?.AlertBanner?.value), [fields?.AlertBanner?.value]);
const [dismissed, setDismissed] = useState(false);
// ...session dismissal and timed auto-hide effects
if (!config || dismissed) return null;
const cta = config.cta?.text && config.cta.url && SAFE_URL.test(config.cta.url.trim()) ? config.cta : null;
return (
<div
className={`alert-banner alert-banner--${config.type} alert-banner--${config.position}`}
style={{
backgroundColor: HEX.test(config.backgroundColor) ? config.backgroundColor : undefined,
color: HEX.test(config.textColor) ? config.textColor : undefined,
}}
role={config.type === 'error' || config.type === 'warning' ? 'alert' : 'status'}
>
<p className="alert-banner__message">{config.message}</p>
{cta && <a className={`alert-banner__cta alert-banner__cta--${cta.style}`} href={cta.url}>{cta.text}</a>}
{/* dismiss button when config.dismissible */}
</div>
);
};

Notice the role. Errors and warnings get alert so screen readers announce them right away, info and success get status so they wait their turn. Small detail, but it’s the kind of thing that gets missed when the banner is just a div someone styled yellow.

What Else Changed in the Refresh

  • Next.js 16 and React 19.2 – plus the Marketplace SDK client 0.5.1 and the XMC module 0.6.0
  • A committed lockfile – a fresh npm install on the old repo failed with a peer dependency conflict between the SDK packages. Needless to say, that’s not a great first impression for a contributor
  • Save closes the dialog – matching the pattern in Sitecore’s own custom field sample, plus a separate Close button
  • Local fonts – builds don’t reach out to Google Fonts anymore
  • CI, a license and a contributing guide – lint, typecheck and build run on every pull request

Come Help

This is the part I’m most excited about. The app is MIT licensed and I’d love for the community to take it further. A few ideas: more icons (or a custom SVG option), scheduling with start and end dates, multiple banners per field, or a site-wide banner pattern using a shared datasource. If you’ve built something similar on a project, I’d like to compare notes.

Remember to:

  • Grab the repo – clone it, run it, register it as a custom app in your Cloud Portal
  • Use the Plugin field type – with your app ID as the Source
  • Validate on both sides – in the editor and again in the renderer
  • Open an issue – bugs, ideas, or just to tell me you’re using it

Grid Composer, the table builder custom field, got the same refresh. I wrote that one up too: Grid Composer: Stop Pasting Tables into Rich Text.

Resources

Alex Lentz

Alex Lentz

Senior Solutions Architect at Americaneagle.com and two-time Sitecore Technology MVP. Building on Sitecore since 2013, mostly SitecoreAI and headless Next.js these days.

LinkedIn    GitHub

Keep reading