Skip to content
Storage guide

Build an Image Upload with Preview and Progress Bar in Next.js

Build a drag-and-drop image uploader with an instant preview and a real progress bar. Files go straight to S3, the key is saved in Postgres, and a gallery shows them with presigned URLs.

25 min Intermediate Markdown for AI

What you'll build

  • A drag-and-drop area that also works with click and keyboard
  • An instant preview with URL.createObjectURL, cleaned up afterwards
  • A real upload progress bar with a Cancel button
  • Type and size checks in the browser and on the server
  • Image keys saved in Postgres and shown in a gallery with presigned URLs

Before you start

  • Node.js 20 or newer
  • A Next.js 16 app using the App Router
  • A way to know who is signed in (see the auth guide)
  • A free CloudHike.dev account
  • Helpful: the presigned upload guide, which explains the basics used here

How the uploader works

The image never passes through your Next.js server. The browser asks your server for a presigned upload URL, sends the file straight to the S3 bucket, then calls a Server Action that checks the file and saves its key in Postgres.

  1. The user drops or picks an image. The browser checks the type and size and shows a preview right away.
  2. A route handler checks the request again and returns a presigned PUT URL.
  3. XMLHttpRequest uploads the file and reports progress as bytes go out.
  4. A Server Action checks the stored object and inserts a row in Postgres.
  5. The gallery reads the rows and signs a short-lived GET URL for each image.

Why not fetch? fetch has no upload progress events. You can only tell when the whole request is done. XMLHttpRequest has upload.onprogress, which works in every browser.

Step 1: Set up storage, Postgres and the helpers

  1. Sign in at cloudhike.dev and create a project.
  2. Click Deploy on the Storage card and on the Postgres card.
  3. Click Copy as .env on each card and paste the values into .env.local.
.env.local
Shell
S3_ENDPOINT=https://...
S3_REGION=...
S3_BUCKET=proj-...
S3_ACCESS_KEY_ID=...
S3_SECRET_ACCESS_KEY=...
DATABASE_URL=postgresql://...
Shell
npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner pg server-only
npm install -D @types/pg

Create the table. Open the project's Postgres card, click Open database, go to the SQL Editor, switch off Read-only and run:

images table
SQL
create table images (
  id bigint generated always as identity primary key,
  user_id text not null,
  key text not null unique,
  content_type text not null,
  size_bytes integer not null,
  created_at timestamptz not null default now()
);

create index images_user_created_idx on images (user_id, created_at desc);

Store the key, not a URL. Presigned URLs expire, but the key is forever. You sign a fresh URL each time you show the image.

Now the server helpers. One shared Postgres pool, kept across dev hot reloads as the Postgres docs recommend:

lib/db.ts
TypeScript
import "server-only";
import { Pool } from "pg";

const globalForDb = globalThis as unknown as { pool?: Pool };

export const pool = globalForDb.pool ?? new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
if (process.env.NODE_ENV !== "production") globalForDb.pool = pool;

And the S3 client. If you followed the presigned upload guide, you already have this file.

lib/s3.ts
TypeScript
import "server-only";
import { DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

export const s3 = new S3Client({
  endpoint: process.env.S3_ENDPOINT,
  region: process.env.S3_REGION,
  forcePathStyle: true,
  // Stops the SDK from signing a checksum of an empty body into
  // presigned PUT URLs, which would make browser uploads fail.
  requestChecksumCalculation: "WHEN_REQUIRED",
  credentials: {
    accessKeyId: process.env.S3_ACCESS_KEY_ID!,
    secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
  },
});

const Bucket = process.env.S3_BUCKET!;

export const createUploadUrl = (key: string, contentType: string) =>
  getSignedUrl(s3, new PutObjectCommand({ Bucket, Key: key, ContentType: contentType }), { expiresIn: 60 });

export const createViewUrl = (key: string) =>
  getSignedUrl(s3, new GetObjectCommand({ Bucket, Key: key }), { expiresIn: 3600 });

export async function getObjectInfo(key: string) {
  try {
    const head = await s3.send(new HeadObjectCommand({ Bucket, Key: key }));
    return { size: head.ContentLength ?? 0, type: head.ContentType ?? "" };
  } catch (err) {
    const e = err as { name?: string; $metadata?: { httpStatusCode?: number } };
    if (e.name === "NotFound" || e.$metadata?.httpStatusCode === 404) return null;
    throw err;
  }
}

export async function deleteObject(key: string) {
  await s3.send(new DeleteObjectCommand({ Bucket, Key: key }));
}

Last, the rules both sides share. This file has no secrets, so the browser can import it too:

lib/images.ts
TypeScript
export const MAX_IMAGE_BYTES = 5 * 1024 * 1024; // 5 MB

// Content type -> file extension. SVG is left out on purpose: an SVG
// can carry scripts, so treat it like any other untrusted document.
export const IMAGE_TYPES = new Map<string, string>([
  ["image/jpeg", "jpg"],
  ["image/png", "png"],
  ["image/webp", "webp"],
  ["image/gif", "gif"],
]);

export const imagePrefix = (userId: string) => `images/${userId}/`;

export function checkImage(file: { type: string; size: number }): string | null {
  if (!IMAGE_TYPES.has(file.type)) return "Please pick a JPEG, PNG, WebP or GIF image.";
  if (file.size > MAX_IMAGE_BYTES) return "That image is over 5 MB.";
  return null;
}

Step 2: Sign uploads on the server

The browser sends the image's type and size, never the file. The route handler checks the user and the file, makes up a key and returns a URL that is valid for one minute.

app/api/images/sign/route.ts
TypeScript
import { randomUUID } from "node:crypto";
import { getUserId } from "@/lib/auth";
import { checkImage, IMAGE_TYPES, imagePrefix } from "@/lib/images";
import { createUploadUrl } from "@/lib/s3";

export async function POST(request: Request) {
  const userId = await getUserId();
  if (!userId) return Response.json({ error: "Please sign in to upload." }, { status: 401 });

  const body = (await request.json().catch(() => null)) as { type?: unknown; size?: unknown } | null;
  const file = {
    type: typeof body?.type === "string" ? body.type : "",
    size: typeof body?.size === "number" ? body.size : 0,
  };
  const problem = file.size <= 0 ? "That image is empty." : checkImage(file);
  if (problem) return Response.json({ error: problem }, { status: 400 });

  const key = `${imagePrefix(userId)}${randomUUID()}.${IMAGE_TYPES.get(file.type)}`;
  try {
    return Response.json({ url: await createUploadUrl(key, file.type), key });
  } catch (err) {
    console.error("Could not sign image upload", err);
    return Response.json({ error: "Could not start the upload." }, { status: 500 });
  }
}

getUserId() is your own session check: it returns the signed-in user's id or null. Browser uploads also need your site in Storage → Settings → Allowed upload domains. Localhost is already allowed in development. See the Storage docs.

Step 3: Build the drag-and-drop uploader with preview and progress

First, a small helper that wraps XMLHttpRequest in a promise. It reports progress from 0 to 100 and can be canceled with an AbortSignal, just like fetch.

lib/upload-with-progress.ts
TypeScript
export function uploadWithProgress(
  url: string,
  file: File,
  onProgress: (percent: number) => void,
  signal?: AbortSignal,
): Promise<void> {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) return reject(new DOMException("Upload canceled", "AbortError"));

    const xhr = new XMLHttpRequest();
    xhr.open("PUT", url);
    // Must match the content type the URL was signed with.
    xhr.setRequestHeader("content-type", file.type);

    xhr.upload.onprogress = (e) => {
      if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100));
    };
    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 300) resolve();
      else reject(new Error(`Upload failed (${xhr.status}).`));
    };
    // CORS problems end up here too, with no status to look at.
    xhr.onerror = () => reject(new Error("Network error while uploading."));
    xhr.onabort = () => reject(new DOMException("Upload canceled", "AbortError"));
    signal?.addEventListener("abort", () => xhr.abort(), { once: true });

    xhr.send(file);
  });
}

Now the component. It keeps one picked file at a time. The preview is a blob: URL that points at the file in memory, so it shows instantly, before any upload. Each one holds the file in memory until it is revoked, so the effect revokes the old URL whenever the preview changes or the component unmounts.

components/image-uploader.tsx
TSX
"use client";

import { useEffect, useRef, useState } from "react";
import { saveImage } from "@/app/images/actions";
import { checkImage, IMAGE_TYPES } from "@/lib/images";
import { uploadWithProgress } from "@/lib/upload-with-progress";

type Status = "idle" | "uploading" | "saving" | "done";

export function ImageUploader() {
  const [file, setFile] = useState<File | null>(null);
  const [preview, setPreview] = useState<string | null>(null);
  const [progress, setProgress] = useState(0);
  const [status, setStatus] = useState<Status>("idle");
  const [error, setError] = useState<string | null>(null);
  const [dragging, setDragging] = useState(false);
  const abort = useRef<AbortController | null>(null);

  // Free the memory behind the old blob: URL.
  useEffect(() => {
    if (!preview) return;
    return () => URL.revokeObjectURL(preview);
  }, [preview]);

  const busy = status === "uploading" || status === "saving";

  function pick(picked: File | undefined) {
    if (!picked || busy) return;
    const problem = checkImage(picked);
    setError(problem);
    setStatus("idle");
    setProgress(0);
    if (problem) {
      setFile(null);
      setPreview(null);
      return;
    }
    setFile(picked);
    setPreview(URL.createObjectURL(picked));
  }

  async function upload() {
    if (!file) return;
    setError(null);
    setStatus("uploading");
    abort.current = new AbortController();
    try {
      const res = await fetch("/api/images/sign", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ type: file.type, size: file.size }),
      });
      const signed = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(signed.error ?? "Could not start the upload.");

      await uploadWithProgress(signed.url, file, setProgress, abort.current.signal);

      setStatus("saving");
      const saved = await saveImage(signed.key);
      if (!saved.ok) throw new Error(saved.error);

      setStatus("done");
      setFile(null);
      setPreview(null);
    } catch (err) {
      setStatus("idle");
      setProgress(0);
      if (err instanceof DOMException && err.name === "AbortError") return;
      setError(err instanceof Error ? err.message : "Upload failed.");
    } finally {
      abort.current = null;
    }
  }

  return (
    <div className="grid max-w-md gap-3">
      <label
        onDragOver={(e) => {
          e.preventDefault(); // needed, or the browser opens the file
          setDragging(true);
        }}
        onDragLeave={() => setDragging(false)}
        onDrop={(e) => {
          e.preventDefault();
          setDragging(false);
          pick(e.dataTransfer.files[0]);
        }}
        className={`grid cursor-pointer place-items-center rounded-lg border-2 border-dashed p-8 text-center ${
          dragging ? "border-blue-500 bg-blue-50" : "border-gray-300"
        }`}
      >
        <input
          type="file"
          accept={[...IMAGE_TYPES.keys()].join(",")}
          className="sr-only"
          disabled={busy}
          onChange={(e) => {
            pick(e.target.files?.[0]);
            e.target.value = "";
          }}
        />
        {preview ? (
          // A blob: URL can't go through the next/image optimizer.
          // eslint-disable-next-line @next/next/no-img-element
          <img src={preview} alt="Preview of the selected image" className="max-h-64 rounded" />
        ) : (
          <span>Drop an image here, or click to choose one</span>
        )}
      </label>

      {busy && (
        <div className="grid gap-1">
          <progress value={progress} max={100} className="w-full" />
          <span className="text-sm">{status === "saving" ? "Saving…" : `${progress}%`}</span>
        </div>
      )}

      <div className="flex gap-2">
        <button type="button" onClick={upload} disabled={!file || busy}>
          Upload
        </button>
        {status === "uploading" && (
          <button type="button" onClick={() => abort.current?.abort()}>
            Cancel
          </button>
        )}
      </div>

      {error && <p role="alert" className="text-red-600">{error}</p>}
      {status === "done" && <p role="status">Uploaded!</p>}
    </div>
  );
}
  • The <label> wraps a hidden <input type="file">, so clicking anywhere in the box opens the file picker, and keyboard and screen reader users still reach the input.
  • onDragOver must call preventDefault(). Without it, the drop event never fires and the browser opens the image in a new tab instead.
  • The <progress> element is accessible out of the box. Style it, or swap in a <div> whose width is ${progress}%.

The browser's file.type comes from the file name's extension, so it is only a hint. The server checks again after the upload, in the next step.

Step 4: Save the image key to Postgres

After the upload, the browser calls a Server Action with the key. The action makes sure the key belongs to this user, looks at the real object in the bucket, and only then inserts the row. A file that breaks the rules is deleted.

app/images/actions.ts
TypeScript
"use server";

import { refresh } from "next/cache";
import { getUserId } from "@/lib/auth";
import { pool } from "@/lib/db";
import { checkImage, imagePrefix } from "@/lib/images";
import { deleteObject, getObjectInfo } from "@/lib/s3";

export type SaveResult = { ok: true } | { ok: false; error: string };

export async function saveImage(key: string): Promise<SaveResult> {
  const userId = await getUserId();
  if (!userId) return { ok: false, error: "Please sign in." };

  // Anyone can call a Server Action with any value, so check it.
  if (typeof key !== "string" || !key.startsWith(imagePrefix(userId)) || key.includes("..")) {
    return { ok: false, error: "Unknown upload." };
  }

  try {
    const info = await getObjectInfo(key);
    if (!info) return { ok: false, error: "The image did not arrive. Please try again." };

    const problem = checkImage(info);
    if (problem) {
      await deleteObject(key);
      return { ok: false, error: problem };
    }

    await pool.query(
      `insert into images (user_id, key, content_type, size_bytes)
       values ($1, $2, $3, $4)
       on conflict (key) do nothing`,
      [userId, key, info.type, info.size],
    );
  } catch (err) {
    console.error("Could not save image", err);
    return { ok: false, error: "Could not save the image. Please try again." };
  }

  refresh(); // re-render the page so the gallery shows the new image
  return { ok: true };
}

refresh() from next/cache tells the client router to fetch the current page again, so the gallery below picks up the new row without a full reload.

Production checklist

  • Add the S3_* variables and DATABASE_URL to your host's environment variables.
  • Add your production origin under Storage → Settings → Allowed upload domains for the production environment. Only localhost is allowed by default in development.
  • Keep the type and size checks on the server. The browser checks are only for friendly messages.
  • Don't accept SVG uploads unless you sanitize them, since they can contain scripts.
  • When a user deletes an image, delete the object with deleteObject(key) and the row together.
  • Uploads that never call saveImage leave stray objects. Clean up keys with no row now and then, for example with a background job.
  • Rate-limit the sign route so one user can't fill your bucket. See rate limiting with Redis.
  • Check storage use and plan limits on the pricing page and the Storage docs.

Frequently asked questions

How do I show upload progress in Next.js?

Upload with XMLHttpRequest instead of fetch and listen to xhr.upload.onprogress. It gives you the bytes sent and the total, so you can show a percentage. fetch only tells you when the whole request has finished.

How do I preview an image before uploading it?

Call URL.createObjectURL(file) and use the result as the src of an img tag. It shows the file from memory right away. Call URL.revokeObjectURL when the preview changes or the component unmounts, or the browser keeps the file in memory.

Can I use next/image with S3 presigned URLs?

Yes, but each new signature is a new URL, so the image optimizer gets few cache hits, and you must add the S3 host to images.remotePatterns. For private images, a plain img tag or next/image with the unoptimized prop is usually the better choice.

Should I store the image URL or the key in the database?

Store the key. Presigned URLs expire, and your storage endpoint could change. Keep the key and sign a fresh URL each time you show the image.

How do I upload several images at once?

Add the multiple attribute to the file input, loop over the files, and run the same sign, upload and save steps for each one. Keep a separate progress value per file, and limit how many upload at the same time, for example three.