Images
@nifrajs/image gives you a CLS-safe, responsive <Image> with lazy-by-default loading and a pluggable loader. The core bundles no image codec - point the loader at a CDN and the runtime stays tiny. Or self-host: the optional @nifrajs/image/server resizes your own images with Bun.Image.
The <Image> component
For string URLs, width and height are required and validated > 0. Imported metadata can supply them automatically. Dimensions reserve layout space so the page never shifts (the CLS contract). It's loading="lazy" + decoding="async" by default; mark the LCP image with priority to get eager + fetchpriority="high". Extra DOM props (className, style, id, data-*) pass straight through to the <img>. Each adapter's /image entry takes @nifrajs/image as an optional peer, so the app installs it beside the adapter.
import { Image } from "@nifrajs/web-react/image"
import { cloudflareLoader } from "@nifrajs/image"
const cdn = cloudflareLoader() // → /cdn-cgi/image/format=auto,width=W/...
export default function Page() {
return <>
{/* The LCP image: priority → loading="eager" + fetchpriority="high"
(React 19 also emits a <link rel="preload" as="image"> for it). */}
<Image src="/hero.jpg" width={1200} height={630} alt="Hero banner"
priority loader={cdn} sizes="(max-width: 1200px) 100vw, 1200px" />
{/* Below the fold: lazy + async-decode by default. width/height
reserve the box, so nothing shifts when it loads (no CLS). */}
<Image src="/thumb.jpg" width={400} height={300} alt="Thumbnail"
loader={cdn} quality={75} />
</>
}The responsive srcSet is built from widths (default [width, width*2] for 1×/2× retina), de-duped and sorted; if every width yields the same URL (e.g. the identity loader), srcSet is omitted. The browser then picks the right candidate for the device's pixel ratio and the sizes you declare.
Local image imports
Opt into ?image imports to read PNG, JPEG, GIF and WebP dimensions at build time, including JPEG, PNG and WebP display orientation. The import is a browser-safe StaticImageDataobject; no filesystem code or codec ships to the browser. Ordinary string URLs are unchanged.
// env.d.ts — enable the typed metadata import:
/// <reference types="@nifrajs/image/imports" />
// routes/index.tsx (React; also supported by Preact, Solid, Vue and Svelte)
import { Image } from "@nifrajs/web-react/image"
import hero from "../shared/images/hero.jpg?image"
export default function Page() {
return <Image src={hero} alt="Mountain lake" priority />
// Optional width={600} infers height from the source aspect ratio.
}// backend/framework.ts — add these beside your existing framework plugins:
import { imageBunPlugin } from "@nifrajs/image/plugins"
const images = { root: process.cwd() }
export const clientPlugins = [imageBunPlugin(images)]
export const serverPlugins = [imageBunPlugin(images)]
// For the Vite pipeline instead (including component mode):
// import { imageVitePlugin } from "@nifrajs/image/plugins"
// export const vitePlugins = [imageVitePlugin(images)]Keep the same image options in client and server builds. Preserve your framework's existing plugins when adding these. Metadata-only imports need no native dependency. Nifra emits the original bytes under /assets/_images/ with content-hashed names, registers them in the build manifest, and serves them in development. Static builds deploy these files too; no image endpoint is needed. For standalone bundler use, emit the plugin'snifraStaticAssets() files yourself. A custom publicPath (a root-relative prefix or an absolute http(s) URL) must match your client build's asset prefix; a mismatch fails the build.
Build-time responsive variants
Supply widths and an explicit ImageBackend to generate real responsive files at build time. This reuses the sharp, Bun.Image or WASM backend seam; sharp is an optional application dependency, not a Nifra runtime dependency. Both the processor and sharp path work on Node without Bun. Outputs support WebP (default), JPEG and PNG; widths never upscale the source.
// doc-check: skip - install sharp and merge with your framework's existing plugins.
import sharp from "sharp"
import { Buffer } from "node:buffer"
import { sharpImageBackend } from "@nifrajs/image/backends"
import { imageBunPlugin } from "@nifrajs/image/plugins"
const images = {
root: process.cwd(),
widths: [320, 640, 1200],
format: "webp" as const,
quality: 80,
backend: sharpImageBackend((bytes) => sharp(Buffer.from(bytes))),
}
export const clientPlugins = [imageBunPlugin(images)]
export const serverPlugins = [imageBunPlugin(images)]
// Vite: use imageVitePlugin(images) in vitePlugins instead.The component chooses only emitted variants; per-render widths filters available candidates rather than creating files. Build-time quality is baked in. An explicit CDN loader overrides the static variant selection. Defaults cap sources at 16 MiB and 40 million pixels; maxSourceBytes and maxSourcePixels are configurable. At most 32 widths, each up to 8192 pixels, are accepted. Sources must remain inside root, including symlink targets. GIF, animated PNG and animated WebP imports are metadata-only; AVIF and SVG metadata imports are not supported.
Loaders
A loader is a pure ({ src, width, quality? }) => string URL builder. Ship with cloudflareLoader() (Cloudflare Images) or the no-op identityLoader, or write your own for any CDN - Imgix, Cloudinary, a signed-URL service, anything.
import type { ImageLoader } from "@nifrajs/image"
import { cloudflareLoader, identityLoader } from "@nifrajs/image"
// Built-in: Cloudflare Images. `base` prepends an origin to bare paths.
const cf = cloudflareLoader({ base: "https://assets.example.com" })
// The default when you pass no loader: no transform (still CLS-safe + lazy,
// just no responsive variants).
identityLoader({ src: "/a.png", width: 800 }) // → "/a.png"
// Any CDN is a pure (src, width, quality?) → URL builder:
const imgix: ImageLoader = ({ src, width, quality }) =>
`https://my.imgix.net${src}?w=${width}&auto=format${quality ? `&q=${quality}` : ""}`Self-hosting - Nifra's own resize endpoint
No CDN? @nifrajs/image/server's createImageHandler is a self-hosted resize endpoint backed by Bun.Image (libjpeg-turbo / libspng / libwebp, decoded off-thread). Pair it with selfHostedLoader and Nifra resizes your own images - no third party in the path.
// 1. The loader (browser-safe) points <Image> at your endpoint:
import { selfHostedLoader } from "@nifrajs/image"
const resize = selfHostedLoader({ endpoint: "/_image" })
// <Image src="/photo.png" width={800} height={450} alt="…" loader={resize} />
// → /_image?src=%2Fphoto.png&w=800 (+ a 1600w retina candidate)
// 2. The endpoint (server-only) does the actual resize with Bun.Image:
import { createImageHandler } from "@nifrajs/image/server"
const image = createImageHandler({
root: "./public", // local sources resolve under here (traversal+symlink guarded)
allowedOrigins: ["https://cdn.example"], // remote sources: allowlist only (omit ⇒ none)
// maxWidth, maxSourceBytes, maxSourcePixels, concurrency, cacheMaxAge - all tunable
// immutable: true, // only for content-versioned source URLs
})
// mount it in your router:
app.get("/_image", (c) => image(c.req))The handler is hardened by default, because src/w/q are untrusted input:
- SSRF, fail-closed. Local sources are confined to
rootwith path-traversal and symlink containment checks; remote sources are refused unless their exact origin is inallowedOrigins(omit it ⇒ no remote fetch at all). Onlyhttp(s)URLs are considered, redirects are refused, and fetches are byte-capped + timed out. - DoS guards. Strict integer parsing (no
Number()coercion), width clamped tomaxWidth, a source byte cap, a decompression-bomb pixel cap (via a cheap header-only probe), and a concurrency semaphore bounding the CPU-heavy codec work. - Correct + cacheable. Never upscales past the intrinsic width; negotiates WebP via
Accept(withVary: Accept); and hashes the emitted bytes for a strongETag, so a changed source at the same URL cannot receive a false304. The mutable-safe default is a one-hourmax-age; opt intoimmutableonly when every source URL is content-versioned.
The handler reads the filesystem, so its local-source path targets Node/Bun servers- but the codec itself is a pluggable ImageBackend, so it runs anywhere (see below).
Backends - Bun, sharp, or WASM (edge)
The codec is a seam: the handler owns all the security above; a backend just decodes/resizes/encodes. Three official backends, all from @nifrajs/image/backends:
bunImageBackend()- the default;Bun.Imageon Bun servers.sharpImageBackend(sharp)- libvips for Node. You pass yoursharpimport (Nifra keeps zero dependency on it, and you pin the version).wasmImageBackend(codecs)- pure-WASM decode/resize/encode you wire up (jSquash is the common choice). The only backend that runs on the edge (Workers / Vercel-Edge / Deno-Deploy), where there's no native codec.@nifrajs/image/backendshas nonode:imports, so it bundles for the edge cleanly; the bomb-safe header probe is built in (it never decodes just to read dimensions).
// doc-check: skip - illustrates third-party codecs (sharp, @jsquash/*); install them to run it.
import { createImageHandler } from "@nifrajs/image/server"
import { sharpImageBackend, wasmImageBackend } from "@nifrajs/image/backends"
// Node - libvips via sharp. Pass your own import (Nifra never depends on it):
import sharp from "sharp"
createImageHandler({ backend: sharpImageBackend(sharp), root: "./public" })
// Edge (Workers / Vercel-Edge / Deno-Deploy) - pure-WASM codecs, e.g. jSquash:
import decodeJpeg from "@jsquash/jpeg/decode"
import resize from "@jsquash/resize"
import encodeWebp from "@jsquash/webp/encode" // + @jsquash/png, @jsquash/jpeg encoders
createImageHandler({
allowedOrigins: ["https://cdn.example"],
backend: wasmImageBackend({
decode: decodeJpeg, // → { data, width, height } (RGBA)
resize: (img, width, height) => resize(img, { width, height }),
encode: async (img, format) => new Uint8Array(await encodeWebp(img)), // switch by format
}),
})Prefer not to run a codec on the edge at all? cloudflareLoader still resizes at the CDN - same <Image>, swap the loader.
Signed URLs
Because src/w/q are attacker-controllable, a public resize endpoint can be resize-bombed - enumerating widths/qualities to flood CPU + cache. Signing shuts that down: set a secret on the loader and the handler, and the endpoint rejects any URL it didn't mint (forged, tampered, or expired) with 403, before any fetch or decode. The signature is a portable synchronous HMAC-SHA256, so the (sync) loader can sign inline - even on the edge.
// Lock the endpoint to URLs YOU minted - kills resize-bombing (w/q enumeration).
// SAME secret on loader + handler; it's server-only (inject from env, like a session secret).
import { selfHostedLoader, signImageUrl } from "@nifrajs/image"
import { createImageHandler } from "@nifrajs/image/server"
const IMAGE_SECRET = process.env.IMAGE_SECRET! // server-only; on Workers read c.env.IMAGE_SECRET instead
const resize = selfHostedLoader({ endpoint: "/_image", secret: IMAGE_SECRET })
// → /_image?src=…&w=800&s=<hmac> (stable: an SSR-signed URL hydrates + caches identically)
const image = createImageHandler({ root: "./public", signing: { secret: IMAGE_SECRET } })
// any request without a valid &s= (forged / tampered / expired) → 403, before any fetch or decode
// Time-limited links to private images (server-side only):
const url = signImageUrl("/_image", { src: "/private/a.jpg", width: 800 }, {
secret: IMAGE_SECRET,
expiresIn: 300, // seconds → adds &exp=
})Signatures over (src, w, q) are stable (no expiry), so an SSR-rendered <Image> srcset hydrates and caches identically. The secret makes a loader config server-only - inject it from env in backend code, never a page or frontend/ module (same discipline as a session secret). For time-limited links to private images, signImageUrl(…, { expiresIn }) adds an &exp= the handler enforces.
Reading intrinsic dimensions
Don't want to hardcode width/height? Read them from the file header in pure JS - no decode, no native dependency - and bake them into a build-time manifest. Supports PNG, JPEG (scans SOFn, skipping earlier segments), GIF, and WebP (VP8 / VP8L / VP8X).
import { imageDimensions, readImageDimensions } from "@nifrajs/image"
// Pure-JS header read - PNG / JPEG / GIF / WebP. No decode, no codec, no deps.
const info = await readImageDimensions(Bun.file("public/hero.jpg"))
// → { width: 1200, height: 630, format: "jpeg" } (null if unrecognized)
// Build-time tooling: pre-read sizes into a manifest so <Image> is CLS-safe
// without hardcoding width/height at every call site. The sync variant takes the
// raw header bytes you already have in memory (no file read):
const headerBytes = await Bun.file("public/hero.jpg").bytes()
imageDimensions(headerBytes)Notes
- The loader is the seam: on the edge, resizing belongs at the CDN (which caches variants and negotiates
format=auto); on a Node/Bun server you can self-host it with@nifrajs/image/serverinstead. Same<Image>, swap the loader. - Always set
sizesfor images that aren't a fixed pixel width, so the browser selects the smallest sufficientsrcSetcandidate. <Image>ships for all five adapters (React, Preact, Vue, Solid, Svelte) - import from@nifrajs/web-<framework>/image. Each builds the same<img>from the agnosticresolveImage(non-React adapters map to lowercase HTML attrs viatoHtmlAttrs).