Skip to main content
Tutorials

Next.js S3 uploads with presigned URLs (without opening up the bucket)

The browser uploads straight to S3 or Garage with a presigned URL your server signs: object key, content type, CORS, size and a check when it's done.

Israel Palma Sebastià

This blog belongs to CREA.MBA, a Next.js boilerplate with auth, payments and an admin panel already set up. See what's included

There are two ways to upload a file from a Next.js app to S3-compatible storage. The first is sending it to your server and having the server upload it: simple, but every file goes through your app, eats memory and runs into request body size limits. The second is having the browser upload it directly to the bucket, with a URL your server signs and that only works for that one upload.

The second option, presigned URLs, is the one you want as soon as files go beyond a few megabytes. Here we build it with the AWS SDK v3, the App Router and Better Auth for the session. It works the same against AWS S3, Cloudflare R2 or Garage on your own server, which is what the CREA.MBA boilerplate uses.

How a presigned URL works

  1. The browser asks your server for permission to upload a file, with its name, type and size.
  2. The server checks the session and the rules (allowed type, max size, user quota), picks the object key and signs a PUT request with its credentials.
  3. The browser sends the PUT straight to storage, with the file as the body.
  4. The browser tells your server it's done, and the server checks the object exists and is what it claimed to be.

The S3 credentials never leave the server. The signed URL carries the signature, date and expiry in its query string, and it's only valid for that key, that method and those signed headers.

The S3 client

// src/lib/storage/s3.ts
import { S3Client } from '@aws-sdk/client-s3';

export const s3 = new S3Client({
  region: process.env.S3_REGION || 'auto',
  endpoint: process.env.S3_ENDPOINT,
  credentials: {
    accessKeyId: process.env.S3_ACCESS_KEY_ID!,
    secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
  },
  forcePathStyle: process.env.S3_FORCE_PATH_STYLE === 'true',
  // Without this, presigned PUT URLs carry a CRC32 checksum of an empty body
  requestChecksumCalculation: 'WHEN_REQUIRED',
});

Three settings that cause trouble with non-AWS storage (and sometimes with AWS itself):

  • S3_REGION. The SDK includes the region in the signature. Garage, for example, has its own in the s3_region setting of its config (garage in its documentation examples and in the boilerplate's), and if the client signs with a different one, Garage rejects the request with an authorization header error. The signature is fine in itself, it's just made for another region.
  • S3_FORCE_PATH_STYLE. With true, URLs look like https://s3.yourdomain.com/bucket/key instead of https://bucket.s3.yourdomain.com/key. On your own server that's usually the convenient choice, because you don't need a subdomain per bucket.
  • requestChecksumCalculation. Since version 3.729.0, the SDK adds a CRC32 checksum to requests by default. In a presigned PUT URL that becomes an x-amz-checksum-crc32=AAAAAA== parameter, which is the CRC32 of an empty body: the SDK doesn't know the file when it signs. Some people see it fail with SignatureDoesNotMatch, others with an unsupported header error on S3-compatible storage. With 'WHEN_REQUIRED' the SDK only computes checksums when the operation requires them and the URL comes out clean. It's worth generating a URL and looking at it before calling the code done.

The signing endpoint

// src/app/api/uploads/presign/route.ts
import { randomUUID } from 'node:crypto';
import { headers } from 'next/headers';
import { PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { z } from 'zod';
import { auth } from '@/lib/auth/server';
import { db } from '@/lib/db/client';
import { s3 } from '@/lib/storage/s3';
import { ALLOWED_TYPES, MAX_BYTES } from '@/lib/storage/limits';

// limits.ts:
// export const ALLOWED_TYPES = { 'image/png': 'png', 'image/jpeg': 'jpg',
//   'image/webp': 'webp', 'application/pdf': 'pdf' } as const;
// export const MAX_BYTES = 10 * 1024 * 1024; // 10 MB

const schema = z.object({
  contentType: z.enum(Object.keys(ALLOWED_TYPES) as [keyof typeof ALLOWED_TYPES]),
  size: z.number().int().positive().max(MAX_BYTES),
});

export async function POST(req: Request) {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) return Response.json({ error: 'Unauthorized' }, { status: 401 });

  const parsed = schema.safeParse(await req.json());
  if (!parsed.success) return Response.json({ error: 'Invalid file' }, { status: 400 });

  const { contentType, size } = parsed.data;
  const key = `users/${session.user.id}/${randomUUID()}.${ALLOWED_TYPES[contentType]}`;

  const uploadUrl = await getSignedUrl(
    s3,
    new PutObjectCommand({
      Bucket: process.env.S3_BUCKET_NAME!,
      Key: key,
      ContentType: contentType,
      ContentLength: size,
    }),
    // content-type isn't signed by default; content-length is, if you pass it
    { expiresIn: 300, signableHeaders: new Set(['content-type']) },
  );

  await db.upload.create({
    data: { key, userId: session.user.id, contentType, declaredSize: size, status: 'PENDING' },
  });

  return Response.json({ uploadUrl, key });
}

Four decisions in this endpoint matter more than the code itself.

The server picks the key. Never use the client's filename as the key. A ../ or a name that collides with another user's file are problems you don't want. A UUID under a per-user prefix avoids collisions and makes it obvious who owns each object. The original filename, if you need it for display, goes in the database.

Type and size are signed. Here's a surprise: setting ContentType on the command is not enough. If you generate the URL with the default options and look at the X-Amz-SignedHeaders parameter, you'll see it only contains host. To make the type part of the signature you have to ask for it with signableHeaders. ContentLength works the other way round: if you include it in the command, the SDK signs it without being asked. With both signed, the URL looks like this: X-Amz-SignedHeaders=content-length;content-type;host. The browser has to send that type and a body of exactly that size (the browser computes Content-Length from the file itself). If they don't match, the signature fails and storage rejects the upload. That way a user can't ask permission for a 200 KB PNG and upload a 2 GB HTML file.

The URL expires quickly. Five minutes is plenty to start an upload. A URL valid for an hour is a URL that can end up in a log, a browser history or someone else's hands for an hour.

The upload leaves a record. With a PENDING row in your own Upload model you know which uploads were requested and never completed, and you can clean up orphaned objects later.

Check when it's done, regardless

The Zod schema validates the size the client says the file has, and the signature forces the body to match it. But every S3-compatible storage implements signature verification its own way, and your app's security shouldn't hinge on a detail you haven't tested on yours. (The classic alternative, a presigned POST with a content-length-range condition in the policy, has the same problem: Garage, for example, implements PostObject according to its compatibility page, but doesn't spell out which conditions it enforces.)

The check that works everywhere is the one at the end: when the browser reports the file is uploaded, the server fetches the object's metadata with HeadObject and compares the real size and type with what was authorized. If they don't match, it deletes it.

// src/app/api/uploads/complete/route.ts
import { DeleteObjectCommand, HeadObjectCommand } from '@aws-sdk/client-s3';
import { headers } from 'next/headers';
import { auth } from '@/lib/auth/server';
import { db } from '@/lib/db/client';
import { s3 } from '@/lib/storage/s3';

export async function POST(req: Request) {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) return Response.json({ error: 'Unauthorized' }, { status: 401 });

  const { key } = await req.json();
  const upload = await db.upload.findFirst({
    where: { key, userId: session.user.id, status: 'PENDING' },
  });
  if (!upload) return Response.json({ error: 'Not found' }, { status: 404 });

  const head = await s3.send(
    new HeadObjectCommand({ Bucket: process.env.S3_BUCKET_NAME!, Key: key }),
  );

  if (head.ContentLength !== upload.declaredSize || head.ContentType !== upload.contentType) {
    await s3.send(new DeleteObjectCommand({ Bucket: process.env.S3_BUCKET_NAME!, Key: key }));
    await db.upload.update({ where: { id: upload.id }, data: { status: 'REJECTED' } });
    return Response.json({ error: 'Invalid file' }, { status: 400 });
  }

  await db.upload.update({
    where: { id: upload.id },
    data: { status: 'READY', size: head.ContentLength },
  });
  return Response.json({ ok: true });
}

Note the where: { key, userId: session.user.id }: a user can only confirm their own uploads. It's the same rule we cover in users only see their own data.

And a warning about the type: ContentType is just a header, and nobody has looked inside the file yet. If your app processes files (resizes images, extracts text from PDFs), validate the actual content when you process it.

The upload from the browser

async function uploadFile(file: File) {
  const res = await fetch('/api/uploads/presign', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ contentType: file.type, size: file.size }),
  });
  if (!res.ok) throw new Error('Could not prepare the upload');
  const { uploadUrl, key } = await res.json();

  const put = await fetch(uploadUrl, {
    method: 'PUT',
    headers: { 'Content-Type': file.type },
    body: file,
  });
  if (!put.ok) throw new Error('Upload failed');

  await fetch('/api/uploads/complete', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ key }),
  });

  return key;
}

The PUT's Content-Type has to match what was signed, character for character. And if the upload fails with SignatureDoesNotMatch, the first thing to do is compare the headers the browser sends (network tab) with the ones listed in X-Amz-SignedHeaders. fetch doesn't report upload progress; if you need a progress bar, use XMLHttpRequest and its upload.onprogress event.

CORS: the error you only see in the browser

A PUT from your domain to s3.yourdomain.com is a cross-origin request. The browser first sends an OPTIONS request (the preflight) and, if the bucket has no CORS rule allowing your origin, the PUT method and the Content-Type header, the upload is cut off before it starts. With curl everything works, because curl doesn't enforce CORS, and that throws people off.

The minimal rule, applied with any S3 client (PutBucketCors, which Garage also implements):

{
  "CORSRules": [
    {
      "AllowedOrigins": ["https://yourdomain.com"],
      "AllowedMethods": ["PUT"],
      "AllowedHeaders": ["Content-Type"],
      "MaxAgeSeconds": 3000
    }
  ]
}
aws s3api put-bucket-cors --bucket my-bucket \
  --cors-configuration file://cors.json \
  --endpoint-url https://s3.yourdomain.com

PutBucketCors replaces the whole configuration, so include in the file every rule you want to keep. And add http://localhost:3000 only to the development bucket.

Serving files: public or signed

Uploading is half the job. For reading, it depends on the kind of file:

  • Public files (avatars, blog images): a bucket or CDN domain with public reads. With Garage there's a non-obvious detail: its S3 API doesn't allow anonymous access, and public reads are served from its web endpoint, with the bucket in website mode and an alias that matches the domain name. We go into detail in the MinIO to Garage migration with Coolify.
  • Private files (invoices, user documents): the bucket stays closed and the server generates a presigned read URL with GetObjectCommand every time the user asks for it, after checking the file is theirs.

Takeaways

  • The browser uploads straight to storage; your server only signs and verifies.
  • The server picks the key and the URL expires in minutes.
  • ContentType isn't signed by default: ask for it with signableHeaders. ContentLength, if you pass it, is.
  • With a recent SDK v3, use requestChecksumCalculation: 'WHEN_REQUIRED' so the URL doesn't carry an empty checksum.
  • Even so, check size and type with HeadObject when the upload finishes.
  • Without a CORS rule on the bucket, the upload fails in the browser even though curl works.
  • With Garage, the client's region has to match the server's.

The CREA.MBA boilerplate ships the S3 client configured through environment variables and Garage in the development docker-compose, with its initial setup script, so storage works locally after a bun storage:setup.

Do you route your users' uploads through the server or straight to the bucket?

Better AuthNext.jsSelf-hostingS3Garage

Enjoyed this article?

Subscribe for more tutorials and tips on building products with AI