Compress images before upload: from 8 MB to 400 KB

Compress images before upload for a Next.js blog: shrink to 1600 px, convert to WebP, strip EXIF and GPS. Real measurements and the sideways-photo trap.

Compressing an image before upload means three things: shrink it to the size the page really needs, convert it to a compact format such as WebP, and strip metadata like the GPS position. The first one saves the most. Would you like an 8.3 MB photo to become about 400 KB? Let's measure it together.

What does one heavy photo do to a free storage plan?

In the previous post, I built a writing box with a preview for the blog. That box only handled text, while a real post has screenshots, and screenshots are often heavy. I need to correct one detail from the previous post, where I wrote that the free storage has 500 MB. According to the Supabase pricing page (which I looked at on 12 November 2026), the Free plan has 500 MB for the database and 1 GB for file storage, counted separately. Images live in file storage, so the right number is 1 GB.

One gigabyte sounds like a lot, but with original photos it runs out fast. With the 8.3 MB test photo I use in this post, 1 GB holds about 120 photos. If every photo weighs only 420 KB, it holds more than two thousand. And that is before you think about readers on a phone, who must download 8.3 MB for every image, a big number on a mobile connection.

This is not just theory for this blog. In the Git history of the project, the commit a60e584 from 4 November 2026 records exactly this problem: uploaded images were stored at full size, and a few screenshots already took several MB each. That commit added a step that shrinks the image in the browser of the author before sending it to Supabase, and its message says that a 14 MB PNG screenshot became about 340 KB. That figure is the one written in the commit, and I did not measure it again. In this post I measure a test image that you can recreate, so you can see which part of the compression matters and which does not.

Preparation: a test image and the measuring code

You need Node.js 22.18 or newer (Node runs .ts files directly from that version). Create a folder compress with the layout below, then run npm install:

Folder layout
compress/
  package.json
  src/make-test-image.ts
  src/image.ts
  src/compress-image.ts
  src/measure.ts
  src/try-rotation.ts
  tmp/            (the test image will live here)
package.json
{
  "name": "compress",
  "private": true,
  "type": "module",
  "dependencies": { "exif-reader": "2.0.2", "sharp": "0.35.5" },
  "devDependencies": { "vitest": "5.1.0" }
}

sharp is an image processing library for Node.js. It is very fast because it uses libvips, written in C, underneath. exif-reader is only there so I can read the metadata in a friendly way.

The first script creates a 6000x4000 test image, like a phone photo: it has detail at many sizes (large colour patches, texture, fine grain) and EXIF metadata with a camera name and a GPS position. I create the image with code, so it is not a real photograph. The compression ratio on your own photos will differ, and even this image comes out slightly different each time you create it (about 8.3 to 8.8 MB in my runs), because it uses random noise:

src/make-test-image.ts
// Create a large test image that looks like a phone photo: detail at many sizes (big colour patches, texture, grain), sensor noise,
// and EXIF metadata with a camera name and a GPS position. The image is generated by code, not a real photo,
// so your numbers will differ from the numbers for your own photos.
// Run: node src/make-test-image.ts <path-to-file.jpg>
import sharp from "sharp";

export const TEST_IMAGE = { width: 6000, height: 4000 };

// One layer of noise at a given "grain size": make small noise, then scale it up. The bigger the grain, the bigger the colour patches.
async function noiseLayer(grainSize: number, amplitude: number): Promise<Buffer> {
  const { width, height } = TEST_IMAGE;
  return sharp({ create: { width: Math.ceil(width / grainSize), height: Math.ceil(height / grainSize), channels: 3, background: "#808080", noise: { type: "gaussian", mean: 128, sigma: amplitude } } })
    .resize(width, height, { kernel: "cubic" }).png().toBuffer();
}

export async function makeTestImage(file: string): Promise<void> {
  const layers = await Promise.all([[400, 70], [120, 60], [40, 55], [12, 50], [4, 40], [1, 22]].map(([grainSize, amplitude]) => noiseLayer(grainSize, amplitude)));
  await sharp(layers[0])
    .composite(layers.slice(1).map((input) => ({ input, blend: "soft-light" as const })))
    .modulate({ saturation: 1.6 })
    .withExif({
      IFD0: { Make: "DemoCam", Model: "Moc-1", Software: "make-test-image.ts" },
      IFD3: { GPSLatitudeRef: "N", GPSLatitude: "10/1 46/1 30/1", GPSLongitudeRef: "E", GPSLongitude: "106/1 42/1 0/1" },
    })
    .jpeg({ quality: 92 })
    .toFile(file);
}

if (import.meta.main) {
  const file = process.argv[2];
  if (!file) throw new Error("Usage: node src/make-test-image.ts <path-to-file.jpg>");
  await makeTestImage(file);
  const info = await sharp(file).metadata();
  console.log(`Created ${file}: ${info.width}x${info.height}`);
}
Create the test image
mkdir tmp
node src/make-test-image.ts tmp/test-image.jpg
Output
Created tmp/test-image.jpg: 6000x4000

Four ways to compress, with real numbers

Before I write the real compression code, I want to know which approach is worth the effort. The script measure.ts takes the same image, compresses it four ways, then prints the size, the time, and whether metadata is still there. It uses the functions fitWithin (shrink by the long side, never enlarge) and formatBytes from src/image.ts. I include that whole file here because later parts use it too:

src/image.ts
// The pure decisions (nothing that touches a real image) of the image compression step. Same logic as src/lib/image-optimize.ts
// in the Tech Notes blog; there the drawing runs in the browser, here we use sharp on Node so it is easy to measure.

// Twice as wide as the article column (720 px) so the image stays sharp on retina screens.
export const MAX_IMAGE_WIDTH = 1600;

// Shrink so the longest side fits `max`, keeping the ratio. Never enlarge.
export function fitWithin(width: number, height: number, max = MAX_IMAGE_WIDTH): { width: number; height: number } {
  const longest = Math.max(width, height);
  if (longest <= max) return { width, height };
  const scale = max / longest;
  return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
}

// A GIF may be animated; recompressing it would freeze it, so leave it alone.
export function shouldOptimize(type: string): boolean {
  return ["image/jpeg", "image/png", "image/webp", "image/avif"].includes(type);
}

// Keep the original if the compressed one is not smaller (the image was already small and well compressed).
// An image that was shrunk in size must use the new version, even if it is heavier, so the stored size matches the article.
export function pickSmaller<T extends { size: number }>(original: T, optimized: T | null, resized: boolean): T {
  if (!optimized) return original;
  if (resized) return optimized;
  return optimized.size < original.size ? optimized : original;
}

export function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
  return `${(bytes / (1024 * 1024)).toLocaleString("en-US", { maximumFractionDigits: 1 })} MB`;
}
src/measure.ts
// Measure: the same image compressed in different ways, how big is each result? Run: node src/measure.ts <image-file.jpg>
import { readFile } from "node:fs/promises";
import exifReader from "exif-reader";
import sharp from "sharp";

import { fitWithin, formatBytes } from "./image.ts";

const file = process.argv[2];
if (!file) throw new Error("Usage: node src/measure.ts <image-file.jpg>");
const original = await readFile(file);
const meta = await sharp(original).metadata();
const exif = meta.exif ? exifReader(meta.exif) : undefined;
console.log(`Original: ${meta.width}x${meta.height}, ${formatBytes(original.length)}, camera: ${exif?.Image?.Make} ${exif?.Image?.Model}, GPS: ${exif?.GPSInfo ? "yes" : "no"}`);

const { width, height } = fitWithin(meta.width!, meta.height!);
const methods: [string, () => Promise<Buffer>][] = [
  ["JPEG q82, original size", () => sharp(original).jpeg({ quality: 82 }).toBuffer()],
  [`JPEG q82, shrunk to ${width}x${height}`, () => sharp(original).resize(width, height).jpeg({ quality: 82 }).toBuffer()],
  [`WebP q82, shrunk to ${width}x${height}`, () => sharp(original).resize(width, height).webp({ quality: 82 }).toBuffer()],
  [`AVIF q50, shrunk to ${width}x${height}`, () => sharp(original).resize(width, height).avif({ quality: 50 }).toBuffer()],
];
for (const [name, run] of methods) {
  const start = performance.now();
  const out = await run();
  const info = await sharp(out).metadata();
  console.log(`${name}: ${formatBytes(out.length)} (${Math.round(performance.now() - start)} ms, EXIF kept: ${info.exif ? "yes" : "no"})`);
}
Measure the four ways
node src/measure.ts tmp/test-image.jpg
Output (your numbers will differ slightly)
Original: 6000x4000, 8.3 MB, camera: DemoCam Moc-1, GPS: yes
JPEG q82, original size: 4.1 MB (158 ms, EXIF kept: no)
JPEG q82, shrunk to 1600x1067: 420 KB (96 ms, EXIF kept: no)
WebP q82, shrunk to 1600x1067: 408 KB (247 ms, EXIF kept: no)
AVIF q50, shrunk to 1600x1067: 203 KB (990 ms, EXIF kept: no)

Here is what I take from these four lines. The first approach, recompressing the JPEG but keeping 6000x4000, brings the image from 8.3 MB down to 4.1 MB, which is half, but still far too heavy for an image inside a post. The second approach, shrinking to 1600 px, is the step that cuts hard: from 4.1 MB to 420 KB, about ten times. The reason is easy to see: the number of pixels falls from 24 million to about 1.7 million, which is more than fourteen times fewer. The article column of the blog is 720 px wide, and I choose 1600 px so the image stays sharp on a retina screen (twice the pixel density), so a reader cannot tell a 1600 px image from a 6000 px one.

What surprised me a little is how close WebP and JPEG are on this image (408 KB against 420 KB). On an earlier run of the same script they came out almost equal (446 KB against 440 KB), so I treat the difference as noise. WebP is often said to be smaller than JPEG, and with real photographs that may be true. But my test image is artificial, so do not conclude from here that WebP is always better. What I am sure about is that you must measure on your own images. AVIF gives the smallest result (203 KB), but it took 990 ms, about four times WebP. For something that happens when the author uploads a picture, one second is fine. If you ran it in bulk on a server, it would be a real cost.

Finally, all four lines say "EXIF kept: no". That is what I explain next.

Metadata and two traps

The first line of the output above shows that the original photo carries a camera name and a GPS position. Photos from a phone often carry the place where they were taken, and if you publish one directly on a public blog, anyone who downloads the picture can read it. When you compress with sharp, metadata is not kept by default, so all four compressed versions are clean. In the compression step of the blog, the browser redraws the image on a canvas, so the result has no EXIF either. I consider this a side benefit that is worth as much as the smaller size.

But dropping metadata is exactly what creates the first trap. EXIF does not only hold the camera name and GPS, it also holds the Orientation tag. A phone often stores a portrait photo as sideways pixels, with a tag that says "rotate 90° when displaying". If you drop EXIF without rotating the pixels first, the image shows up sideways. The script below creates such an image and shows two ways of handling it, using the function compressImage that I give right after:

src/try-rotation.ts
// A portrait photo from a phone is often stored as sideways pixels plus an EXIF Orientation = 6 tag ("rotate 90° when displaying").
// If you drop EXIF without rotating the pixels first, the image ends up sideways. Run: node src/try-rotation.ts
import sharp from "sharp";

import { compressImage } from "./compress-image.ts";

const portraitPhoto = await sharp({ create: { width: 3000, height: 2000, channels: 3, background: "#c0392b" } })
  .jpeg().withMetadata({ orientation: 6 }).toBuffer();

const meta = await sharp(portraitPhoto).metadata();
console.log(`Original: pixels ${meta.width}x${meta.height}, Orientation ${meta.orientation} (an image viewer will display ${meta.height}x${meta.width})`);

const wrong = await sharp(portraitPhoto).resize({ width: 1600, height: 1600, fit: "inside" }).webp().toBuffer({ resolveWithObject: true });
console.log(`Drop EXIF, no rotation: ${wrong.info.width}x${wrong.info.height}, no Orientation left, so the image displays sideways`);

const right = await compressImage(portraitPhoto);
console.log(`compressImage (rotate first): ${right.width}x${right.height}`);
Try a portrait photo
node src/try-rotation.ts
Output
Original: pixels 3000x2000, Orientation 6 (an image viewer will display 2000x3000)
Drop EXIF, no rotation: 1600x1067, no Orientation left, so the image displays sideways
compressImage (rotate first): 1067x1600

Lines two and three are the ones to look at: for the same image, the blunt way of dropping EXIF gives 1600x1067 (landscape, wrong), while compressImage gives 1067x1600 (portrait, right). This is the function compressImage, where everything comes together:

src/compress-image.ts
// Compress one image: rotate it upright using EXIF, shrink to at most 1600 px, convert to WebP. Metadata (camera, GPS) is not kept.
import sharp from "sharp";

import { fitWithin, MAX_IMAGE_WIDTH, pickSmaller } from "./image.ts";

export type Result = { buffer: Buffer; type: string; width: number; height: number; size: number };

export async function compressImage(input: Buffer, max = MAX_IMAGE_WIDTH): Promise<Result> {
  // rotate() with no argument: rotate the pixels according to the EXIF Orientation tag. Do this before dropping EXIF, or a portrait photo ends up sideways.
  const upright = await sharp(input).rotate().toBuffer({ resolveWithObject: true });
  const { width, height } = fitWithin(upright.info.width, upright.info.height, max);
  const resized = width !== upright.info.width;
  const webp = await sharp(upright.data).resize(width, height).webp({ quality: 82 }).toBuffer({ resolveWithObject: true });
  const optimized: Result = { buffer: webp.data, type: "image/webp", width, height, size: webp.data.length };
  const format = (await sharp(input).metadata()).format;
  const original: Result = { buffer: input, type: `image/${format}`, width: upright.info.width, height: upright.info.height, size: input.length };
  return pickSmaller(original, optimized, resized);
}

The function does four things: it rotates the pixels according to EXIF (rotate() with no argument), computes the new size with fitWithin, converts to WebP at quality 82, and then uses pickSmaller to choose. The second trap is in the last step. For an image that is already small and well compressed, say 40x40 pixels, compressing again can produce a bigger file, and choosing that one would defeat the purpose. So pickSmaller keeps the original if the compressed one is not smaller. There is one deliberate exception: if the image was shrunk in size, the new version must be used, even if it is heavier, because the dimensions recorded in the post must match the real file.

GIF is the third case. A GIF file may be animated, and recompressing it as a still image would freeze it. The function shouldOptimize lets only JPEG, PNG, WebP and AVIF go through compression, and a GIF is uploaded untouched.

Tests that lock the decisions

All the decisions above can go wrong silently: no error shows up, the image is just heavier or sideways. So I write a test for each. Here are the tests for compressImage (the test file for the pure functions in image.ts has more edge cases, such as a small image not being enlarged):

src/compress-image.test.ts
import sharp from "sharp";
import { expect, test } from "vitest";

import { compressImage } from "./compress-image.ts";

const image = (width: number, height: number, orientation?: number) =>
  sharp({ create: { width, height, channels: 3, background: "#3366cc" } }).jpeg().withMetadata(orientation ? { orientation } : {}).toBuffer();

test("a large image is shrunk to 1600 px and converted to WebP", async () => {
  const result = await compressImage(await image(4000, 3000));
  expect(result).toMatchObject({ type: "image/webp", width: 1600, height: 1200 });
});

test("a portrait photo (Orientation 6) is rotated upright before EXIF is dropped", async () => {
  const result = await compressImage(await image(3000, 2000, 6));
  expect(result.width).toBe(1067);
  expect(result.height).toBe(1600);
  expect((await sharp(result.buffer).metadata()).orientation).toBeUndefined();
});

test("a small image that is not smaller after compression keeps the original", async () => {
  const original = await sharp({ create: { width: 40, height: 40, channels: 3, background: "#fff" } }).webp({ quality: 1, effort: 6 }).toBuffer();
  const result = await compressImage(original);
  expect(result.buffer).toBe(original);
});
Run the tests
npx vitest run src/compress-image.test.ts
Output
 Test Files  1 passed (1)
      Tests  3 passed (3)

In the demo repo there is also a file image.test.ts with nine more tests for the pure functions (shrinking by the long side, never enlarging, a flat image not rounding down to 0, the four cases of pickSmaller, GIF and formatBytes). Running both files gives 12 green tests. You can write them yourself from the rules in image.ts, because each function is small.

So where does this blog compress: in the browser or on the server?

In this post I run sharp on Node because it is easy to measure, but the Tech Notes blog compresses right inside the browser of the author, before the image goes onto the network. The reason is that I want to send as few bytes as possible when the author uploads, and I do not want to run an image processing function on the server just to trim a picture that the author will never upload again. Here is an excerpt of the function that redraws the image in src/components/admin/editor/upload-image.ts of the blog (I kept the English comments of the original file):

src/components/admin/editor/upload-image.ts (excerpt)
async function encode(bitmap: ImageBitmap, width: number, height: number): Promise<Blob | null> {
  // Redrawing also drops EXIF metadata (camera, GPS location) from phone photos.
  if (typeof OffscreenCanvas !== "undefined") {
    const canvas = new OffscreenCanvas(width, height);
    const context = canvas.getContext("2d");
    if (!context) return null;
    context.drawImage(bitmap, 0, 0, width, height);
    try {
      const blob = await canvas.convertToBlob({ type: OPTIMIZED_TYPE, quality: WEBP_QUALITY });
      return blob.type === OPTIMIZED_TYPE ? blob : null;
    } catch {
      return null;
    }
  }
  // (a fallback branch using a normal canvas and toBlob, same approach)
}

Two things to notice. First, drawImage paints onto a canvas, so the metadata disappears on its own, exactly as the comment says. Second, the line blob.type === OPTIMIZED_TYPE ? blob : null guards against a browser that cannot encode WebP and silently returns another format. In that case the function returns null, and pickSmaller keeps the original image, so the editor never saves an image heavier than the one it received. The functions fitWithin, shouldOptimize and pickSmaller in src/lib/image-optimize.ts of the blog are the originals of what you just ran, which is why they can be tested on Node.

Compressing on the server is also reasonable, especially when users are not trusted authors, or when you want several sizes for several screens. The price is that the image function runs on your server and costs time and memory. The next/image component of Next.js also shrinks images, but it does so when the image is served to a reader, and the original 8.3 MB file stays untouched in your storage. So it solves page loading, not a full storage bucket.

The image is light now, but how will readers find the blog?

By now the blog has a safe writing editor, images are slim, and the storage is enough for thousands of pictures. But one thing is left: Google does not know this blog exists, and the posts have no titles, descriptions or sitemap for search engines to read. How to make a Next.js blog findable is the job of the next posts.

You can follow the whole series at Build a blog with Next.js + Supabase. If you are preparing for interviews, the questions about Next.js, React and web performance are in the interview question bank.

Get the next post by email.

One email a week, only when there is something worth reading. No spam.