Build an Image Thumbnail Service With Node.js
Build an on-demand thumbnail service in Node.js with sharp: validated widths, path traversal protection, WebP output and a disk cache keyed by request.

Serving full-size photos to a grid of small cards wastes bandwidth and slows pages. The usual cure is a thumbnail service: a URL such as /thumb?src=cat.jpg&w=256 returns a resized image, and the first request for each size does the work while later ones come from a cache. This post builds that service in Node.js 26 'Lithium', the LTS line since 2026-10-28, with the same code working on the 24 and 22 maintenance lines. Node.js has no image codec built in, so the resizing uses the sharp package, which wraps libvips and ships prebuilt binaries for common platforms. Everything else, the HTTP server, hashing and file access, is built in.
Design before code
An image service is an attractive target, because it takes input from the URL and does expensive work with it. Three rules shape the design before any resizing happens.
Only allow a fixed list of widths. If
wcan be any number, a client can request every width from 1 to 10000 and fill your disk with variants, or ask for a giant size to burn CPU.Resolve the source path against one root directory and reject anything that escapes it. Otherwise
src=../../etc/passwdis a request to read files outside the images folder.Cache by the validated request, not by the raw query string, so
w=256&src=a.jpgandsrc=a.jpg&w=256share one cached file.
These are the same lessons as any file-serving endpoint. The allowed-width list is also a product decision: pick the sizes your layout really uses, such as 64, 128, 256 and 512, and the cache stays small and predictable.
Validating the request
The parsing function is pure, which makes it easy to check. It returns either a validated request or an error string, and it never touches the file system.
import path from "node:path";
export const WIDTHS = [64, 128, 256, 512];
export function parseRequest(rawUrl, root) {
const url = new URL(rawUrl, "http://localhost");
const src = url.searchParams.get("src");
const width = Number(url.searchParams.get("w"));
if (!src) return { error: "missing src" };
if (!WIDTHS.includes(width)) return { error: "width not allowed" };
const full = path.resolve(root, src);
if (!full.startsWith(root + path.sep)) return { error: "path outside root" };
return { file: full, width };
}
const root = "/srv/images";
console.log(parseRequest("/thumb?src=cat.jpg&w=256", root));
console.log(parseRequest("/thumb?src=cat.jpg&w=300", root));
console.log(parseRequest("/thumb?src=../etc/passwd&w=64", root));
console.log(parseRequest("/thumb?w=64", root));The first request is valid, so the function returns the absolute file path and the width. The second asks for 300, which is not in the list. The third tries to climb out of the root: path.resolve("/srv/images", "../etc/passwd") yields /srv/etc/passwd, which does not start with /srv/images/. The fourth has no src. Paths here are POSIX; on Windows the separator and drive letters differ, but the logic is the same because path.sep is used.
{ file: '/srv/images/cat.jpg', width: 256 }
{ error: 'width not allowed' }
{ error: 'path outside root' }
{ error: 'missing src' }The startsWith(root + path.sep) check is deliberate. Testing startsWith(root) alone would accept /srv/images-private/secret.jpg, because that string begins with /srv/images. Adding the separator closes that gap. Also remember that path.resolve does not follow symbolic links. If a link inside the images folder points outside it, the check passes. Either forbid links in that folder or call fs.realpath on the result and check again.
The cache key
A cache key must be stable, short and safe to use as a file name. Hashing the file path, the width, and the source file's modification time gives all three, and it has a pleasant side effect: when someone replaces cat.jpg, its modification time changes, so the key changes and the old thumbnail is never served. Without the modification time you would need to purge by hand.
import { createHash } from "node:crypto";
import { stat } from "node:fs/promises";
export async function cacheKey(file, width) {
const info = await stat(file);
const input = `${file}:${width}:${info.mtimeMs}:webp`;
return createHash("sha256").update(input).digest("hex").slice(0, 24) + ".webp";
}
const key = await cacheKey(import.meta.filename, 256);
console.log(key.length);
console.log(key.endsWith(".webp"));The digest is hex, so its characters are always safe in a file name. Cutting it to 24 characters keeps names short and leaves 96 bits of space, far more than a thumbnail cache will ever fill. Adding the extension makes the format visible when you list the cache directory. The key length is 24 characters plus the five of .webp.
29
trueThe format is in the key because output format is part of the identity. If you later add AVIF, a different key keeps WebP and AVIF thumbnails apart.
Resizing with sharp
The resize is one chained call. It reads the source, scales to the requested width while keeping the aspect ratio, refuses to enlarge a smaller image, and encodes WebP. Rotating by the embedded orientation tag matters for phone photos, which are often stored sideways with a flag.
import sharp from "sharp";
export function makeThumbnail(file, width) {
return sharp(file)
.rotate()
.resize({ width, withoutEnlargement: true })
.webp({ quality: 80 })
.toBuffer();
}withoutEnlargement means a 100 px wide source requested at 256 comes back at 100, not blurry at 256. toBuffer returns a promise for the encoded bytes. Because sharp strips metadata by default, GPS coordinates in the original EXIF data do not leak into the thumbnail, which is a quiet privacy benefit worth keeping.
The quality number is a trade-off you choose. Lower values give smaller files and visible artifacts. Pick a value by looking at your own images, since results depend on the content.
The server with a disk cache
The handler ties the pieces together. It validates, computes the key, serves from the cache directory when the file exists, and otherwise renders, writes the file and responds. An x-cache header reports which path ran, which is handy while testing.
import { createServer } from "node:http";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { parseRequest } from "./params.js";
import { cacheKey } from "./cache-key.js";
import { makeThumbnail } from "./resize.js";
const ROOT = path.resolve("images");
const CACHE = path.resolve("cache");
await mkdir(CACHE, { recursive: true });
function send(res, status, headers, body) {
res.writeHead(status, headers);
res.end(body);
}
const server = createServer(async (req, res) => {
const parsed = parseRequest(req.url, ROOT);
if (parsed.error) return send(res, 400, { "content-type": "text/plain" }, parsed.error);
try {
const cached = path.join(CACHE, await cacheKey(parsed.file, parsed.width));
try {
const bytes = await readFile(cached);
return send(res, 200, { "content-type": "image/webp", "x-cache": "hit" }, bytes);
} catch (err) {
if (err.code !== "ENOENT") throw err;
}
const bytes = await makeThumbnail(parsed.file, parsed.width);
await writeFile(cached, bytes);
send(res, 200, { "content-type": "image/webp", "x-cache": "miss" }, bytes);
} catch (err) {
if (err.code === "ENOENT") return send(res, 404, { "content-type": "text/plain" }, "not found");
console.error(err.message);
send(res, 500, { "content-type": "text/plain" }, "error");
}
});
server.listen(3000, () => console.log("thumbnails on 3000"));With a file images/cat.jpg present, asking for the same size twice shows the cache working. The command curl -s -o /dev/null -w "%{http_code} %header{x-cache}\n" "http://localhost:3000/thumb?src=cat.jpg&w=256" needs curl 7.84 or newer for the %header{} format. First call:
200 missSecond call, same URL:
200 hitA request for a width outside the list returns 400 with the text width not allowed, and a request for a file that does not exist returns 404, because stat in cacheKey throws ENOENT before any resize work starts.
Putting it in front of real traffic
Add long-lived caching headers, such as Cache-Control: public, max-age=31536000, immutable, but only when the URL changes whenever the image does. That holds if you include a version or hash in the query string; with plain src and w, use a shorter lifetime. Put a CDN in front, so most requests never reach Node.js at all. Limit concurrent resizes, because sharp decodes large images in native memory, and a burst of cache misses can use a lot of it. A simple counter or a small queue that allows a few resizes at once keeps memory flat.
Two concurrent misses for the same thumbnail will both render it. For low traffic that only wastes a little CPU. To avoid it, keep a map from cache key to in-flight promise, and let the second request await the first. Write the cache file to a temporary name and rename it, so a reader never sees a half-written image.
Where this service stops
This design serves a modest image library from local disk. It does not support remote sources, which would need an allow-list of hosts and size limits to avoid becoming an open proxy. It does not crop, which is a separate decision about focal points. It never evicts old thumbnails, so the cache grows with every new source file. And it trusts the source files: decoding untrusted uploads deserves its own limits on dimensions and pixel counts. For a team that needs all of that, a managed image CDN or a maintained image proxy is cheaper than growing this code.
Testing and monitoring the service
The pure functions are the easy part to test: feed parseRequest a list of good and hostile URLs and assert the results, including encoded dots such as %2e%2e%2f and absolute paths like /etc/passwd. The URL class decodes the query string before your code sees it, so those cases reach the path check as plain ../, which is exactly what you want to verify. Add a test for a symbolic link that points outside the root if you allow links at all.
For the resizing and caching, use two small fixture images and assert on the response headers and on the decoded size of the result, which sharp can report through its metadata call. Check that a second request is a hit, and that touching the source file produces a miss again, which proves the modification time is part of the key.
In production, watch three signals. The cache hit ratio tells you whether your list of widths matches what clients actually request. The time spent on misses tells you whether resizing is the bottleneck, and the memory of the process tells you whether concurrent decodes are too many. Log the validated width and the source name for each miss, never the full query string, and review the list of requested sources now and then, because a spike of requests for names that do not exist is a scanner probing your path handling.
Finally, decide what happens when a source image is corrupt. sharp throws, the handler returns a 500, and the next request tries again and fails again. Cache a short-lived failure marker, or return a placeholder image, so a single bad upload does not burn CPU on every page view.


