Skip to content

Live tiles that never crash the page

Date
Type
Guide
Reading time
8 minutes

The homepage of this site is a grid of tiles, and a few of them are live. One shows what I’m listening to on Last.fm, with a record that spins while a track plays. Another draws my GitHub contributions for the last six months. A third is a map.

Every one of those depends on a service I don’t control. Last.fm has bad days. GitHub rate-limits. An API can rename a field on a Tuesday and tell nobody. I can forget to set an environment variable on a new deploy.

None of that is allowed to take the page down. The repo guide has a heading for it, “The rule that matters most”, and the rule is that nothing external may crash the page. The worst an outage can do is make one tile look empty.

This guide is how that rule is enforced. The answer is five boring layers, each with one job, and the music tile is the example all the way through.

The path every request takes

Every third-party call follows the same route, top to bottom:

lib/schemas/*.ts      zod schema for the upstream wire format
lib/http.ts           fetchJson(): fetches, times out, validates, never throws
lib/services/*.ts     domain logic, returns Result<T, Error>
app/api/*/route.ts    thin adapter, always responds 200
components/*          reads the envelope, renders a fallback when ok is false

The point of splitting it like this is that each layer can assume the one below it did its job. The component never wonders whether the JSON was valid. The service never wonders whether the request timed out. Nobody wraps anything in a defensive try because they’re nervous.

Layer 1: a schema that expects to be lied to

Last.fm’s recent-tracks endpoint is a good teacher. Ask for several tracks and track is an array. In some single-track responses it’s a bare object instead. Album and artwork can be missing entirely.

You could handle all of that in the component with optional chaining everywhere. I’d rather absorb it once, at the edge, with a zod schema:

const textNodeSchema = z
	.object({ "#text": z.string().catch("") })
	.catch({ "#text": "" });

const lastFmTrackSchema = z.object({
	name: z.string().catch(""),
	url: z.string().catch(""),
	artist: textNodeSchema,
	album: textNodeSchema,
	image: z
		.array(
			z.object({
				size: z.string().catch(""),
				"#text": z.string().catch(""),
			}),
		)
		.catch([]),
	"@attr": z
		.object({ nowplaying: z.string().optional() })
		.optional()
		.catch(undefined),
	date: z.object({ uts: z.string() }).optional().catch(undefined),
});

export const lastFmRecentTracksSchema = z.object({
	recenttracks: z.object({
		track: z
			.union([z.array(lastFmTrackSchema), lastFmTrackSchema])
			.transform((track) => (Array.isArray(track) ? track : [track]))
			.catch([]),
	}),
});

The important part is .catch(). Without it, one malformed field fails the whole parse, and a missing album name blanks the tile. With it, a broken field falls back to an empty value and everything around it survives. Cosmetic fields get a .catch(). Fields the tile can’t live without don’t, so a genuinely broken payload still fails loudly.

The array-or-object mess is normalised right there too. Everything downstream gets a list, always.

Layer 2: one fetch function that never throws

There is exactly one place in the app that calls fetch for an upstream API, and it’s fetchJson in lib/http.ts. Its whole contract is in the return type:

export async function fetchJson<T>(
	url: string,
	options: FetchJsonOptions<T>,
): Promise<Result<T, HttpError>>

It never throws. Instead, every way a request can go wrong becomes a named kind of failure:

export type HttpFailureKind =
	| "timeout"
	| "network"
	| "http-status"
	| "invalid-json"
	| "invalid-shape";

Each failure is caught at the step where it happens. The request gets AbortSignal.timeout() with an eight-second default, so a hung upstream can’t hang the render. A non-2xx status is a failure. A body that isn’t JSON is a failure. A body that is JSON but doesn’t match the schema is a failure too, and that one matters most, because it’s the silent kind. Every branch logs with a scope label and returns.

Result itself is tiny:

export type Result<T, E = Error> =
	| { readonly ok: true; readonly data: T }
	| { readonly ok: false; readonly error: E };

The reason to return this instead of throwing is that TypeScript won’t let you touch data until you’ve checked ok. A thrown error is easy to forget about. A Result sits in your way until you deal with it.

Layer 3: the service decides what failure means

The service is where domain decisions live, and the most useful one in getMusic() is about a missing API key:

const apiKey = process.env.LASTFM_API_KEY;
const username = process.env.LASTFM_USERNAME;

if (!apiKey || !username) {
	return ok({ music: null, fetchedAt: Date.now() });
}

No key is a configuration choice, not an outage. So it returns success with nothing to show, and the tile renders an idle turntable that says “Not listening to anything right now.” That’s a calm, true sentence. A missing key shouldn’t make the site look broken on a preview deploy.

An actual failed request is different. That comes back from fetchJson as a failed Result, and the service passes it straight up:

const result = await fetchJson(url, {
	schema: lastFmRecentTracksSchema,
	revalidate: REVALIDATE_SECONDS,
	scope: "last-fm",
});

if (!result.ok) return result;

Services also carry import "server-only", so an API key can’t end up in a client bundle by accident. The build fails if a client component imports one.

Layer 4: the route handler always says 200

The browser polls /api/last-fm to keep the tile fresh. When Last.fm is down, the obvious thing is to return a 502. I don’t, and of all the decisions here, this is the one that looks wrong at first.

A 5xx with an error body is something the client has to special-case, and if it doesn’t, it crashes. So every route returns an envelope with a renderable payload:

export interface ApiEnvelope<T> {
	ok: boolean;
	data: T;
	reason?: string;
	fetchedAt: number;
}

When things work, ok is true. When they don’t, degraded() builds the same shape with a safe fallback in data and the cause in reason. The route handler stays tiny:

export async function GET() {
	const body = await getMusicEnvelope();

	return NextResponse.json(body, {
		headers: {
			"Cache-Control": body.ok
				? "public, max-age=0, s-maxage=10"
				: "no-store",
		},
	});
}

Look at the cache header. A good answer is cached at the edge for ten seconds. A degraded one is never cached, so a thirty-second Last.fm blip doesn’t get pinned on a CDN and served to everyone for longer than it lasted.

Layer 5: the tile keeps the last good answer

The homepage server-renders the music tile with a real envelope, so the first paint already has a track in it, even without JavaScript. Then a small client component takes over and polls: every 10 seconds while a track is playing, every 30 while it isn’t, never while the tile is off-screen or the tab is hidden.

When a poll fails, the tile doesn’t throw away what it has. The polling hook keeps the last successful data and sets an error alongside it. The tile keeps showing the track and adds one line underneath:

Can’t reach Last.fm right now. Updated 3 minutes ago.

This is the part I like most. An outage turns into one honest sentence about freshness. Only when there has never been a good answer does the tile fall back to “Music is unavailable right now.”

The last line: one error boundary per tile

Everything above handles failures I expected. Bugs are the failures I didn’t. A tile might hit a value it can’t render and throw on the client.

A string of round light bulbs. Every bulb glows except one dark bulb in the middle.
Wired in parallel. One bulb goes out and the rest keep shining.

So the bento wraps every tile in its own error boundary:

<ErrorBoundary
	key={key}
	scope={`bento:${key}`}
	fallback={<TileFallback name={TILE_NAMES[key]} />}
>
	<TileShell tileKey={key} />
</ErrorBoundary>

If the music tile throws, the music tile becomes a plain card that says “Music is unavailable.” It keeps its exact slot in the grid, so nothing shifts. The other tiles never find out. Error boundaries still have to be class components in React, which feels a bit old-fashioned in 2026, but it’s about 40 lines and it never changes.

On the server, tiles aren’t allowed to throw at all. Their data comes from services that return a Result, so an upstream failure is just another state to render. A real bug there fails the build. And if a background revalidation fails in production, Next.js keeps serving the last good HTML.

The trap: don’t reach for Suspense

This is the part that isn’t obvious, and it’s why there’s a comment in the bento explaining what isn’t there.

The natural move with async server components is to wrap each one in Suspense so a slow tile doesn’t hold up the rest. On this page that backfires. Once the HTML gets past React’s first progressive chunk (around 12.8 KB, and the homepage is past it), React streams completed Suspense boundaries out of line. The initial HTML holds each tile’s fallback, and the real content arrives as a hidden copy that a script swaps in.

With JavaScript, that means a flash of fallbacks until the next animation frame. Without JavaScript, the swap never happens. Every visitor with scripts off would see a grid where every tile says it’s unavailable, on a page that rendered perfectly well on the server.

So the tiles render inline, and slow upstreams are handled by timeouts and caching instead. fetchJson gives up after eight seconds. The homepage itself is regenerated in the background at most once a minute, so a visitor is served HTML that already exists and never waits on Last.fm.

Tests that read like the rules

The failure paths are tested directly, and the test names read like the rules they protect:

an upstream failure is a failed result, not a throw
missing keys mean nothing to show, without calling Last.fm
a single track sent as a bare object becomes a list of one
one malformed field does not cost the track or its neighbours
a failed hue never fails the envelope

That last one is about the album-art colour. The tile tints itself from the artwork’s dominant hue, which means fetching and decoding an image on the server. It’s purely decorative, so it resolves to null on any failure, and a broken image can never cost you the track name.

Adding a new live tile

If you’re building something similar, this is the checklist I follow:

  1. Write a zod schema for the upstream response. Put .catch() on every field the UI could live without.
  2. Call the API through one fetchJson-style function with a timeout, and return a Result.
  3. In the service, decide which conditions are “nothing to show” and which are real failures. A missing key is usually the first kind.
  4. Have the route handler return an envelope with a renderable fallback, always with status 200, and don’t cache degraded responses.
  5. Server-render the first envelope. On the client, keep the last good data when a poll fails and say how old it is.
  6. Wrap the tile in its own error boundary with a fallback the same size as the tile.
  7. Write the failure tests first. They’re the ones that matter on the day something breaks.

It’s more code than await (await fetch(url)).json(). For every integration I write a schema, a service, a route and a client component, where one function would technically work. I think that’s the right trade. The extra files are small and boring, and on the day Last.fm goes down, the only sign on my homepage is one quiet line under a song title.