Menu

An image upload endpoint in Fastify: five checks before decode
📰

An image upload endpoint in Fastify: five checks before decode

DEV Community: fastify·Sahadat Husain·15 days ago
#yAW2gTK5
#devtofastify#devto#dev#file#error
Reading 0:00
15s threshold

An image upload route should refuse bad files before it decodes a single pixel. Five checks do it in Fastify: cap the bytes, allow one file, sniff the magic bytes, read the header's dimensions, and only then decode with a pixel cap and a time cap. On my machine the route refused a 400-megapixel PNG bomb in 1.7 ms. The same route took 130.4 ms to decode and re-encode a normal 1920 × 1280 photo.

Why check before decode?

Decoding is where an image costs you. A compressed file says nothing about its decoded size. I made a 20000 × 20000 PNG of one flat colour with sharp. It is 1,211,460 bytes on disk. Decoded as RGB, it is 400 million pixels, 1.2 GB of raw samples.

Every check below runs on bytes you already hold, or on the file header.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.