Skip to content

Private previewMost of the architecture is written. First public release in 2027.

@hamur/image

The first-party image module. Add it to modules and set its options under the image config key. It gives one pair of plain functions, getImage and getSizes, that build image URLs from the config: the same output on the server and in the browser, with no hook and no $img.

ts
// hamur.config.ts
export default defineConfig({
  modules: ["@hamur/image"],
  image: {
    format: ["webp"],
    quality: 75,
    domains: ["images.example.com", "https://cms.example.com/uploads/**"],
    presets: { avatar: { modifiers: { width: 64, height: 64, fit: "outside" } } },
  },
});
ts
import { getImage, getSizes } from "@hamur/image/react";

getImage("/photos/a.jpg", { width: 600 }).url;
// /_hamur/image/q_75,v_3f9a01c2,w_640/photos/a.jpg.webp
getSizes("/photos/a.jpg", { sizes: "100vw md:50vw" });
// { src, srcset: "… 640w, … 768w, … 1200w", sizes: "(min-width: 768px) 50vw, 100vw", width: 1200, height: 800 }

default

The module, as defineModule({ meta: { name: "image", configKey: "image" } }). Its setup checks the options (a wrong value is a build error naming the key) and writes three virtual modules: #hamur/image/options (the part of the config a URL needs, so the browser holds no dir, maxPixels or prerender), #hamur/image/providers (an import of each provider in use, and none other) and #hamur/image/sources (one entry per image file of the source dirs: size, format and the v_ hash).

Under hamur dev and on the presets whose features.imageTransforms is not unsupported (bun) the setup also adds the route that serves hamur URLs, GET and HEAD /_hamur/image/** (below app.baseURL, after public files); on every other preset the same URLs are files written at build (below), and a server preset answers an unwritten one with GET /_hamur/image/** 404 image variant not generated at build; add its source to image.prerender or use a provider (the static preset has no route).

Build variants

Where the hamur provider has no run-time transform (every preset whose features.imageTransforms is unsupported, outside hamur dev) and the build uses it, prerender:done writes each variant as a public file under .output/public/_hamur/image/: every /_hamur/image/… URL in a prerendered page's src, srcset, imagesrcset, preload href and style url(), plus image.prerender. Variants are made with Bun.Image.backend = "bun", so a build on any OS writes the same bytes, and cached in node_modules/.cache/hamur/image/. The log ends [image] 214 variants (12 new, 202 from cache). A source that is missing or refused fails the build naming the page: image: /_hamur/image/w_640/missing.jpg.webp (in /about): source "/missing.jpg" not found; a remote source whose URL has a query string fails with image: <url> has a query string, which a file cannot carry; use a provider for this source.

The /_hamur/image/ route

/_hamur/image/<modifiers>/<source>.<jpg|png|webp> reads the source below the source dir, decodes it with Bun.Image (at most image.maxPixels pixels), applies rot_, flip, flop and the resize (w_, or fit_fill, fit_inside, fit_outside with h_ and w_, never enlarging) and encodes it in the extension's format with q_ as the quality. The result is kept in useStorage("cache") under a key of the source's content, the modifiers and the extension, and answered with that key as etag, cache-control: public, max-age=31536000, immutable when the URL is pinned (v_, or an asset URL source), public, max-age=3600 otherwise and no-cache under hamur dev; If-None-Match answers 304. A built server answers only the files the build listed in #hamur/image/sources; an image.dir outside public/ is shipped with the server, not in .output/public/. A 200 is always bytes the route encoded, never the source's own.

Refusals are text/plain with an image: message: 400 for a URL in another spelling (image: modifiers must be sorted and given once (write "h_200,w_300")), an unknown key, a value out of range, image: width 1234 is not an allowed size (image.widths, or the source's own width), image: fit "cover" is not made here (fill, inside, outside), image: output extension ".gif" is not made here (jpg, png, webp), image: source path escapes the source dir, image: source is SVG, which this endpoint does not transform; link it directly, image: source is not a JPEG, PNG or WebP image and image: source could not be decoded; 404 image: source "/photos/a.jpg" not found, and from a built server image: source "/photos/a.jpg" has no version v_00000000 for a v_ that is not the listed hash; 413 image: source exceeds image.maxPixels; 403 image: remote host evil.test is not in image.domains.

A remote source (_https/<host>/<path>, _http/… with a URL pattern, plus the route URL's query) is fetched only when image.domains or an alias target allows it. The host's addresses must not be loopback, private, link-local or unspecified, else 403 image: remote host resolves to a private address, and the request goes to the checked address. At most 3 redirects are followed, each target checked again (403 image: remote redirect to evil.test is not allowed). The fetch stops after 10 s (504 image: remote source timed out after 10 s) and after image.maxBytes bytes (413 image: remote source is larger than image.maxBytes). A non-2xx answer is 502 image: remote source answered 404. A remote result is cached by its URL and the upstream strong etag (else the hash of its bytes) and answered public, max-age=3600; for that hour a repeat request asks the upstream nothing, and concurrent requests for one URL share one fetch.

A source below image.sources.blob.prefix (/_hamur/image/w_64/blob/avatars/1.png.png with the prefix /blob/) is a @hamur/blob key, the rest of the decoded path (avatars/1.png), read with useBlob() and never looked up in public/. Every key below the prefix is publicly readable through /_hamur/image/: no guard the app puts around useBlob().serve applies, so keep private keys outside the prefix. A key with an empty segment, .., an encoded / or a \ answers 400 image: source path escapes the source dir, one over 1024 bytes 400 image: blob key is longer than 1024 bytes; a missing blob, or a key with a segment starting with ., 404 image: blob "avatars/1.png" not found; one larger than image.maxBytes 413 image: blob source is larger than image.maxBytes. The cache key holds the hash of the blob's bytes, remembered for 60 s, so a repeat or a 304 within that minute does not read the store, and a blob put again is served at the latest a minute later; the answer is public, max-age=3600. Blob sources are transformed where the route runs (bun, bun-compile, hamur dev); on a preset that transforms at build the build warns [image] image.sources.blob needs run-time transforms; the node preset transforms at build, so blob sources are served untransformed and getImage and getSizes return such a src as it is.

ImageOptions

KeyTypeDefault
provider"auto" | "hamur" | "none" | "vercel" | "netlify" | "cloudflare" | a hosted provider (below) | string"auto": vercel on the vercel presets and netlify on the netlify presets, hamur everywhere else and under hamur dev
providersRecord<string, { provider?: string; options?: Record<string, unknown> }>{}: provider is a built-in name (default: the key) or the path of a custom provider file
presetsRecord<string, { provider?: string; modifiers: ImageModifiers }>{}
screensRecord<string, number>{ sm: 640, md: 768, lg: 1024, xl: 1280, "2xl": 1536 }; keys merge over the defaults
densitiesnumber[][1, 2]; each from 1 to 4
widthsnumber[]every screens value times every density, plus 64, 128, 256, 384; every width is rounded up to this list
formatImageFormat[]["webp"]; in order of preference
qualitynumberunset; 1 to 100
domainsstring[][]: a host pattern (cdn.example.com, *.example.com one label, **.example.com any depth) allows https and every path; a URL pattern (http://cdn.example.com:8080/img/**) fixes scheme, port and path
aliasRecord<string, string>{}: a src starting with a key is that URL plus the rest, allowed as if listed in domains
dirstringthe public dirs
maxPixels, maxBytesnumber50000000, 26214400: the most pixels a source may have (413) and the most bytes read from a remote or blob source (413)
prerenderstring[][]: build variants beyond the prerendered pages: a /_hamur/image/… URL, or a source path or glob below the source dir (/photos/**), which gives every widths entry up to the source's width, and its own, in each of format that hamur makes
sources{ blob?: { prefix: string } }{}: a src below prefix (starting and ending with /, not / and not below /_hamur/) is a @hamur/blob key, publicly readable; without @hamur/blob in modules the load fails with image.sources.blob needs "@hamur/blob" in modules

The load errors name the key: image.densities must be numbers from 1 to 4 (got 0.5), image.domains[0] "*" allows every host; name the hosts, image.screens.md must be a positive integer (got 0), image.format[0] "gif" is not an output format (avif, webp, jpeg, png), image.alias key "cms" must start with "/", image.dir "assets/img" does not exist. A provider option named key, secret or salt fails with would be sent to every browser; signed URLs are not supported.

ImageModifiers, ImageFormat, ImageFit

ts
type ImageFormat = "avif" | "webp" | "jpeg" | "png";
type ImageFit = "cover" | "contain" | "fill" | "inside" | "outside";
interface ImageModifiers {
  width?: number; height?: number; fit?: ImageFit; format?: ImageFormat; quality?: number;
  rotate?: 90 | 180 | 270; flip?: boolean; flop?: boolean;
  [provider: string]: string | number | boolean | undefined;
}

ImageProvider, ImageProviderContext

ts
interface ImageProvider {
  formats: readonly ImageFormat[];
  negotiates: boolean;
  fits: readonly ImageFit[];
  modifiers: readonly string[];
  getImage(src: string, ctx: ImageProviderContext): string;
}
interface ImageProviderContext { modifiers: ImageModifiers; options: Record<string, unknown>; baseURL: string }

A provider turns a source and modifiers into a URL. The built-ins are hamur (jpeg, png, webp; fits fill, inside, outside; rotate, flip, flop) and none (the src as given), and the platform services vercel, netlify and cloudflare, which negotiate the format from Accept and take their widths and sizes from the build.

image.providers, image.presets

ts
// hamur.config.ts
image: {
  provider: "mycdn",
  providers: {
    mycdn: { provider: "./app/image-provider.ts", options: { base: "https://img.example.com" } },
    cloudinary: { options: { cloudName: "demo" } },
  },
  presets: { avatar: { provider: "mycdn", modifiers: { width: 64, height: 64, fit: "cover" } } },
}

image.providers.<name> is { provider?, options? }: provider is a built-in name (default: the key) or a path resolved from the app root; the file default-exports an object satisfies ImageProvider and is bundled only when the config names it. image.presets.<name> is { provider?, modifiers }; preset="avatar" on Img and Picture and getImage(src, modifiers, { preset: "avatar" }) start from its modifiers, and the props and the call's modifiers win key by key. Errors: at load image.provider "x" is not "auto", "hamur", "none", a built-in provider or a key of image.providers, image.providers.a.provider "./x.ts" does not exist; at use image provider "mycdn" (./app/image-provider.ts) has no getImage, image: no provider named "x" (configured: hamur, cloudinary), image: no preset named "x" (configured: avatar).

HamurImageProviders, HamurImagePresets, HamurImageProvider, HamurImagePreset

The registries typegen fills (provider name → true, preset name → true) and the unions over them, the types of the provider and preset props and of getImage's options. While a registry is empty, the union is string.

Hosted providers

cloudinary, imgix, imagekit, cloudflareImages, bunny, fastly, sanity, storyblok, contentful, strapi, supabase, uploadcare, twicpics, imgproxy and weserv build the URL of a hosted image service. Name one as image.provider: "<name>" or under image.providers.<name>, with its options in image.providers.<name>.options; only the providers a build names are in its bundles. A required option that is missing throws at the first URL: image.providers.cloudinary.options.cloudName is required.

ProviderOptionsSource
cloudinarycloudName (required), origin (https://res.cloudinary.com)a public id; a remote src is fetched
imgixorigin (required)a path of the source; a remote src goes through a web proxy source
imagekitorigin (required, the URL endpoint)a path; a remote src follows the endpoint
cloudflareImagesaccountHash (required), origin (https://imagedelivery.net)an image id; flexible variants must be on; a remote src is returned as it is
bunnyorigin (required, the pull zone)a path; a remote src is returned as it is
fastlyorigin (unset: the app's own domain)a path, or a remote URL of the service
sanityprojectId (required), dataset (production), origin (https://cdn.sanity.io)a file name, or an asset URL
storyblokorigin (https://a.storyblok.com)an asset path or https://a.storyblok.com/f/… URL; the operations follow it after /m/
contentfulorigin (https://images.ctfassets.net)/<space>/<id>/<token>/<name>, or an asset URL
strapiorigin (unset: the app's own domain)an upload path; the responsive file of the smallest breakpoint (500, 750, 1000) that is at least width
supabaseorigin (required, the project URL)/<bucket>/<path> of a public bucket, or its object URL
uploadcareorigin (https://ucarecdn.com)/<uuid>/ or a CDN URL; quality is the nearest of the named levels lightest, lighter, normal, better, best
twicpicsorigin (required)a path of the domain
imgproxyorigin (required)a remote URL, or a local path read as local:///<path>; unsigned /insecure/ URLs only, so the service must restrict its sources
weservorigin (https://wsrv.nl), sourceURL (required for a local src)a remote URL, or a local path below sourceURL

A provider makes only the formats, fits and transforms its service documents; the others degrade as in getImage. imgproxy refuses an option named key, secret or salt at load, like every provider.

ImageSizes, ImageMeta

ImageSizes is { src: string; srcset?: string; sizes?: string; width?: number; height?: number }. ImageMeta is the core type of a ?meta import, re-exported.

@hamur/image/server, @hamur/image/react, @hamur/image/vue, @hamur/image/preact, @hamur/image/svelte, @hamur/image/solid, @hamur/image/html

Every entry exports getImage and getSizes; they read the generated modules, so a handler and a component get one answer. The five component entries (react, vue, preact, svelte, solid) and html also export Img.

getImage

ts
function getImage(src: string | ImageMeta, modifiers?: ImageModifiers, options?: { provider?: string; preset?: string }): { url: string }

The preset's modifiers, then the call's (a key the call sets wins). The provider is options.provider, else the preset's, else image.provider. Before the provider runs: a width is rounded up to image.widths, then capped at the source's own width when it is known (an ImageMeta, or a file of the source dir), with height scaled by the same factor; height is sent only with fit; a fit the provider does not make drops height and fit (under hamur dev one [image] line per source names it); rotate, flip, flop or a key the provider lacks throw image provider "hamur" does not support rotate; format is the first of image.format the provider makes, else the source's own. A source the provider does not transform (SVG, GIF, AVIF, HEIC, ICO, TIFF, an animated image) gives its own URL.

The hamur URL is <app.baseURL>_hamur/image/<modifiers>/<source>.<ext>: the modifiers sorted by key (fit, flip, flop, h, q, rot, v, w) or _, a local file below the source dir, _https/<host>/<path> for a remote source (its query string follows the URL), and the output format as the extension. v_<8 hex> pins a file of the source dir by its content. A remote src that image.domains does not allow (an alias expansion is exempt) is returned as it is, untransformed, with one [image] remote image host evil.test is not in image.domains; served untransformed line per host under hamur dev. The platform URLs, for width 640, quality 80 and format webp: vercel /_vercel/image?url=%2Fa.jpg&w=640&q=80 (q is quality or 75, which Vercel requires; no w gives the src), netlify /.netlify/images?url=%2Fa.jpg&w=640&fm=webp&q=80 (fits cover, inside as contain, fill; h and fit follow w) and cloudflare /cdn-cgi/image/width=640,quality=80,format=webp/a.jpg (format=auto when none; fits cover, inside as contain, contain as pad). auto never picks cloudflare: it needs Image Transformations turned on for the zone, so name it with provider: "cloudflare".

On a vercel or netlify build that uses their provider the module writes no /_hamur/image route and no variants, and puts the service's settings into the config the preset writes. .vercel/output/config.json gets images: { sizes: image.widths, domains: [], remotePatterns, formats, qualities, minimumCacheTTL: 14400 } (qualities is 75, image.quality and each preset's quality; the provider sends only widths of image.widths): remotePatterns is one { protocol, hostname, port, pathname } per image.domains entry and alias target (* and ** kept, a target covers everything below its path), formats the avif and webp entries of image.format as MIME types. .netlify/v1/config.json gets images.remote_images, one anchored expression per entry (** any text, * one host label or one path segment, an optional query string allowed). vercel.config.images and netlify.config.images in the app's config are merged under these keys; a scalar Hamur writes wins and an array holds both the app's entries and Hamur's. On Netlify an existing .netlify/v1/config.json keeps its other keys. An image.alias target with a query string, a fragment or credentials fails at load.

Unknown names throw image: no provider named "imgix" (configured: hamur, none) and image: no preset named "hero" (configured: avatar).

getSizes

ts
function getSizes(src: string | ImageMeta, options: {
  sizes?: string; width?: number; height?: number; densities?: number[];
  modifiers?: ImageModifiers; provider?: string; preset?: string;
}): ImageSizes

With sizes ("100vw md:50vw xl:400px": [<screen>:]<n>vw|px), srcset has one w descriptor per slot width times density, rounded and capped, ascending, and sizes is (min-width: 1280px) 400px, (min-width: 768px) 50vw, 100vw. With width alone it has x descriptors (two densities that round to one width keep the lower) and src is the 1x URL. With neither, src is the source with the other modifiers. width and height are the options, else the source's own size, the missing one from the aspect ratio. A source that is not transformed gives src, width and height only. A sizes error names the string: image: sizes "100vw tablet:50vw": "tablet" is not a key of image.screens.

Img

tsx
import { Img } from "@hamur/image/react";

<Img src="/a.png" width="300" sizes="sm:100vw md:50vw" alt="" />;
// <img src="/_hamur/image/v_3f9a01c2,w_1200/a.png.webp" srcset="… 640w, … 768w, … 1200w"
//      sizes="(min-width: 768px) 50vw, (min-width: 640px) 100vw, 100vw" width="300" height="200"
//      alt="" loading="lazy" decoding="async">

An <img> whose src, srcset and sizes are what getSizes gives for the props. With modules: ["@hamur/image"] the component is registered as Img in the React, Preact, Vue, Svelte and Solid apps (with components: false import it from @hamur/image/<library>); html has no tags, so there Img(props): string is imported and its string placed in the page.

PropTypeDefault
srcstring | ImageMetarequired: a path below the source dir, an asset URL, a remote URL, an alias path or a ?meta object
altstringrequired in the types; "" for a decorative image
width, heightnumber | \${number}``the source's size when known; the width and height attributes and the transform size
sizesstringnone; the syntax of getSizes
densitiesnumber[]image.densities
format, quality, fitImageFormat, number, ImageFitimage.format, image.quality, none
modifiersImageModifiersnone
provider, presetstringimage.provider, none
loading"lazy" | "eager""lazy"; "eager" with preload
fetchpriority"high" | "low" | "auto"unset; "high" with preload; fetchPriority in React
preloadbooleanfalse
placeholderstringnone; a URL or data URL painted as the <img>'s background until it loads
placeholderClassstringnone; a class on the <img> until it loads
load, erroronLoad, onError (React, Preact, Solid), @load, @error (Vue), onload, onerror (Svelte); html has nonenone
custom renderchildren: (state) => … (React, Preact), function child (Solid), custom prop or default scoped slot (Vue), children snippet (Svelte), custom: (state) => string (html)the <img>

preload is for the page's LCP image. It pushes <link rel="preload" as="image" href imagesrcset imagesizes fetchpriority> into the head, keyed image:<src URL>, so two Img of one source give one link, and sets loading="eager" and fetchpriority (the prop, else high) on the <img>. Picture with preload preloads its first <source> and adds its type, which a browser that cannot decode the type skips; without a <source> it preloads the <img> as Img does.

placeholder adds style="background-image: url(<placeholder>); background-size: cover; background-position: center; background-repeat: no-repeat" to the <img> in the server HTML (the app's own style wins) and placeholderClass adds a class. In React, Preact, Vue, Svelte and Solid both are removed on load, also for an image complete before hydration; html keeps them, so give it no transparent image. import blur from "./hero.jpg?placeholder" gives a data URL (see Assets); Picture takes the same two props. There is no placeholder: true.

load and error run the app's handler once per src. An image the browser finished before the page hydrated fires load once after hydration (error when it has no pixels). A custom render receives { imgAttrs, src, isLoaded } (see ImgState) and writes its own markup; spread imgAttrs on an <img> to keep the attributes and, in a client library, the load and error listeners.

tsx
<Img src="/a.png" width="300" alt="">{({ src, isLoaded }) => <div data-src={src} data-loaded={isLoaded} />}</Img>;

Every other <img> attribute (class, id, title, data-*) is passed through after these, className in React. There is no nonce: a CSP nonce governs scripts and styles, not images. A width or height that is not a number of pixels throws image: <Img src="/a.png"> width "50%" must be a number of pixels. Under hamur dev one line per src is logged for a missing alt ([image] <Img src="/a.png"> has no alt; pass alt="" for a decorative image) and for an image whose size is unknown ([image] <Img src="https://cms.example.com/a.jpg"> has no width and height; the layout shifts when it loads).

Picture

tsx
import { Picture } from "@hamur/image/react";

<Picture src="/a.png" width="300" sizes="sm:100vw md:50vw" alt="" format="webp" />;
// <picture>
//   <source type="image/webp" srcset="… 640w, … 768w, … 1200w" sizes="(min-width: 768px) 50vw, (min-width: 640px) 100vw, 100vw">
//   <img src="/_hamur/image/v_3f9a01c2,w_1200/a.png.png" srcset="… a.png.png 1200w" sizes="…" width="300" height="200" alt="" loading="lazy" decoding="async">
// </picture>

Img's props with two changes. format is one ImageFormat or a list (default image.format): the result has one <source type="image/<format>" srcset sizes> per entry the provider can make, in order, except legacyFormat. legacyFormat (default png for a PNG source, else jpeg) is the format of the <img>, which is the fallback every browser reads. Every other prop and attribute goes on the <img>, as with Img; there is no imgAttrs. A provider with formats: [] (none, vercel) and a source that is not transformed (an SVG, an animated WebP) render the <img> alone, without <picture>. With modules: ["@hamur/image"] the component is registered as Picture in the React, Preact, Vue, Svelte and Solid apps; html imports Picture(props): string.

PictureProps

The props type of Picture in @hamur/image/react, /preact, /solid and /html: ImgProps with format?: ImageFormat | ImageFormat[] and legacyFormat?: ImageFormat. The Vue component declares the same props; the Svelte component takes them from HTMLImgAttributes.

ImgState

What a custom render of Img receives, exported from @hamur/image/react, /preact, /solid and /html: { imgAttrs: Record<string, unknown>; src: string; isLoaded: boolean }. imgAttrs holds the attributes of the <img> (srcSet and fetchPriority in React), and in a client library its load and error listeners and a ref (onload, onerror in Svelte); src is the computed src; isLoaded is true after load and false before it and after error. In html, imgAttrs is Record<string, string> and isLoaded is always false.

ImgProps

The props type of Img in @hamur/image/react, /preact, /solid and /html: ImgOptions (src, alt, width, height, sizes, densities, format, quality, fit, modifiers, provider, preset, loading, preload, placeholder, placeholderClass), the library's priority prop (fetchPriority in React, fetchpriority elsewhere), the custom render (children in React, Preact and Solid, custom in html) and the attributes of its <img> element ([attribute: string]: unknown in html). The Vue component declares the same props; the Svelte component takes them from HTMLImgAttributes.