Skip to content

An image proxy with edge caching and sized covers in Next.js

Why Melodius serves every album cover from its own origin: a host allowlist, signed and unsigned tokens, five fixed widths, WebP, and separate browser and Cloudflare cache lifetimes.

3 min read

A music app shows hundreds of album covers per screen. In Melodius, none of them load from a provider's CDN directly. They go through one route on Melodius's own origin. This is why, and how it stays fast.

Why proxy artwork at all

  • One origin for every cover, so apps and the web never depend on a provider's CDN behaviour.
  • Covers are resized and re-encoded once, then cached, instead of shipping 1000-pixel originals to 64-pixel thumbnails.
  • If a source should stop showing artwork, it can be switched off in one place.

Tokens and the allowlist

The route is /api/image/[token]. The token encodes the provider URL. Apps receive signed tokens; the web builds unsigned ones in the browser, without the secret. Either way, the decoded URL must point to an authorised artwork host, or it is never fetched. The allowlist is the real gate: without it the route would be an open proxy.

typescript
const url = resolveArtworkToken(token) ?? resolveUnsignedArtworkToken(token);
if (url === null) return notFound(3600); // not ours, or a host that may no longer show artwork

Five widths, not infinite

?w= asks for a width, and the server serves the listed width at or above it: 64, 128, 256, 512 or 1000. Thumbnails ask for 256, the player and headers for 1000, the OS media session for 512 and colour sampling for 64. A fixed set keeps the cache small and hit rates high; arbitrary widths would let anyone fill the cache with variants.

Two caches, two lifetimes

text
Cache-Control:               public, max-age=604800, stale-while-revalidate=86400  (browsers, apps: 1 week)
Cloudflare-CDN-Cache-Control: public, max-age=86400,  stale-while-revalidate=604800 (edge: 1 day)

Browsers keep a cover for a week. Cloudflare keeps it for a day, so a source switched off disappears within a day everywhere. Misses get short negative caching: an hour for tokens that will never resolve, five minutes when the provider did not answer, so the apps retry later.

Headers for an untrusted image

The bytes come from a third party, so the response is locked down: X-Content-Type-Options: nosniff, a Content-Security-Policy of default-src 'none'; sandbox, and an explicit cross-origin resource policy. Even if a provider served something unexpected, the browser would not run it.

Illustrated avatar of Kumar Manas

Written by Kumar Manas

Full-stack developer in India. I build Melodius and Krypton.

Related projectMelodius: music streaming platform