What you'll build
- A server-only S3 client and helpers for signed upload and download links
- A route handler that checks file type and size, then returns a presigned PUT URL
- A browser upload that sends the file straight to the bucket
- A check after upload, and downloads through presigned GET URLs
- Browser uploads allowed for your domain, and the CORS error explained
Before you start
- Node.js 20 or newer
- A Next.js 16 app using the App Router (
npx create-next-app@latest) - A way to know who is signed in (any auth library, or the auth guide)
- A free CloudHike.dev account
How presigned uploads work
The simple way to upload is to post the file to your own server, which then sends it to S3. That works for small files, but every byte passes through your app. Server Actions also cap the request body at 1 MB by default, and serverless hosts have their own request size limits.
A presigned URL avoids all of that. Your server uses its secret key to sign a URL that allows one action, such as "PUT this key, with this content type, for the next 60 seconds". The browser sends the file to that URL. Nobody can reuse it for anything else, and the key never leaves the server.
- The browser asks your route handler for an upload URL and sends the file's type and size.
- The route handler checks the user, the type and the size, picks a key, and signs a
PUTURL. - The browser
PUTs the file straight to the bucket. - The browser tells your server the upload is done. The server checks the stored object and keeps or deletes it.
- Later, the server signs a
GETURL whenever someone should download the file.
| Approach | Good | Watch out for |
|---|---|---|
| Upload through your server | Simple, one request | Body size limits, slow on serverless, you pay for the bandwidth twice |
| Presigned PUT URL | Any file size, fast, nothing big touches your server | Needs CORS on the bucket, and a check after upload |
Step 1: Create a bucket and copy the keys
- Sign in at cloudhike.dev and create a project.
- Click Deploy on the Storage card. You get a private bucket and an access key that only works on that bucket.
- Click Copy as .env and paste the values into
.env.localat the root of your Next.js app.
S3_ENDPOINT=https://...
S3_REGION=...
S3_BUCKET=proj-...
S3_ACCESS_KEY_ID=...
S3_SECRET_ACCESS_KEY=...Never prefix these with NEXT_PUBLIC_. The secret key can read and delete every file in the bucket, so it must stay on the server.
The Storage docs explain each variable.
Step 2: Create a server-only S3 client
Install the AWS SDK v3 S3 client and its URL signer. They work with any S3-compatible storage, not just AWS.
npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner server-onlyPut the client and all signing in one file. The server-only import makes the build fail if a Client Component ever imports it.
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,
// Put the bucket name in the path, not in the host name.
forcePathStyle: true,
// Recent SDK versions add a checksum of an empty body to presigned
// PUT URLs, and the real upload then fails. Only add checksums when
// S3 requires them.
requestChecksumCalculation: "WHEN_REQUIRED",
credentials: {
accessKeyId: process.env.S3_ACCESS_KEY_ID!,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
},
});
const Bucket = process.env.S3_BUCKET!;
// The content type is part of the signature, so the browser must send
// exactly this type or the upload is refused.
export function createUploadUrl(key: string, contentType: string) {
return getSignedUrl(s3, new PutObjectCommand({ Bucket, Key: key, ContentType: contentType }), {
expiresIn: 60, // seconds
});
}
export function createDownloadUrl(key: string, downloadName?: string) {
const safeName = downloadName?.replace(/[^\w.\- ]/g, "_");
return getSignedUrl(
s3,
new GetObjectCommand({
Bucket,
Key: key,
// Ask the browser to save the file instead of opening it.
ResponseContentDisposition: safeName ? `attachment; filename="${safeName}"` : undefined,
}),
{ expiresIn: 300 },
);
}
// Size and type of a stored object, or null if it does not exist.
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 }));
}Next, put the upload rules in a file without server-only, so the browser can check files with the same rules before it asks for a URL:
// Shared by the browser and the server. No secrets in here.
export const MAX_UPLOAD_BYTES = 10 * 1024 * 1024; // 10 MB
// Allowed content types and the file extension we store them under.
// A Map, so a type like "__proto__" can never match by accident.
export const ALLOWED_TYPES = new Map<string, string>([
["image/jpeg", "jpg"],
["image/png", "png"],
["image/webp", "webp"],
["application/pdf", "pdf"],
]);
export const userPrefix = (userId: string) => `uploads/${userId}/`;Step 3: Check the file and return a presigned PUT URL
This route handler is the gatekeeper. It decides who may upload, what they may upload, and where the file goes. The browser only sends the file's type and size, never the file.
import { randomUUID } from "node:crypto";
import { getUserId } from "@/lib/auth";
import { createUploadUrl } from "@/lib/s3";
import { ALLOWED_TYPES, MAX_UPLOAD_BYTES, userPrefix } from "@/lib/uploads";
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 type = typeof body?.type === "string" ? body.type : "";
const size = typeof body?.size === "number" ? body.size : 0;
const ext = ALLOWED_TYPES.get(type);
if (!ext) {
return Response.json({ error: "That file type is not allowed." }, { status: 415 });
}
if (size <= 0 || size > MAX_UPLOAD_BYTES) {
return Response.json({ error: "That file is too big." }, { status: 413 });
}
// Never use the user's file name as the key: it can clash, overwrite
// someone else's file or contain odd characters. Generate one instead.
const key = `${userPrefix(userId)}${randomUUID()}.${ext}`;
try {
const url = await createUploadUrl(key, type);
return Response.json({ url, key });
} catch (err) {
console.error("Could not sign upload", err);
return Response.json({ error: "Could not start the upload. Please try again." }, { status: 500 });
}
}getUserId() stands in for your own session check. It should return the signed-in user's id, or null. Every key starts with uploads/<userId>/, which makes it easy to check later that a user only touches their own files.
A presigned PUT URL locks the key, the content type and the expiry, but not the file size. The size the browser sends here is only a claim. Step 5 checks the real size after the upload.
Step 4: Upload from the browser
The upload form asks for a URL, sends the file with fetch, then tells the server it is done. Send the same content-type you signed, or S3 rejects the request with SignatureDoesNotMatch.
"use client";
import { useState } from "react";
import { ALLOWED_TYPES, MAX_UPLOAD_BYTES } from "@/lib/uploads";
async function postJson<T>(url: string, body: unknown): Promise<T> {
const res = await fetch(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error ?? `Request failed (${res.status})`);
return data as T;
}
export function FileUpload() {
const [status, setStatus] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [key, setKey] = useState<string | null>(null);
async function upload(file: File) {
// Quick checks for a friendly message. The server checks again.
if (!ALLOWED_TYPES.has(file.type)) return setStatus("Please pick a JPEG, PNG, WebP or PDF file.");
if (file.size > MAX_UPLOAD_BYTES) return setStatus("That file is over 10 MB.");
setBusy(true);
setStatus("Uploading…");
setKey(null);
try {
const signed = await postJson<{ url: string; key: string }>("/api/uploads", {
type: file.type,
size: file.size,
});
const put = await fetch(signed.url, {
method: "PUT",
headers: { "content-type": file.type },
body: file,
});
if (!put.ok) throw new Error(`Upload failed (${put.status}).`);
await postJson("/api/uploads/complete", { key: signed.key });
setKey(signed.key);
setStatus("Uploaded!");
} catch (err) {
// A CORS problem shows up here as a TypeError: "Failed to fetch".
setStatus(err instanceof Error ? err.message : "Upload failed.");
} finally {
setBusy(false);
}
}
return (
<div className="grid max-w-md gap-3 p-8">
<input
type="file"
accept={[...ALLOWED_TYPES.keys()].join(",")}
disabled={busy}
onChange={(e) => {
const file = e.target.files?.[0];
if (file) upload(file);
e.target.value = ""; // allow picking the same file again
}}
/>
{status && <p role="status">{status}</p>}
{key && <a href={`/api/download?key=${encodeURIComponent(key)}`}>Download it</a>}
</div>
);
}Render <FileUpload /> on any page. Want a drag-and-drop area, an image preview and a progress bar? The image upload guide builds on this one.
Step 5: Check the upload and download with a presigned GET
Once the browser says the upload is done, look at what actually landed in the bucket. HeadObject returns the real size and type without downloading the file. Anything that breaks the rules is deleted.
import { getUserId } from "@/lib/auth";
import { deleteObject, getObjectInfo } from "@/lib/s3";
import { ALLOWED_TYPES, MAX_UPLOAD_BYTES, userPrefix } from "@/lib/uploads";
export async function POST(request: Request) {
const userId = await getUserId();
if (!userId) return Response.json({ error: "Please sign in." }, { status: 401 });
const body = (await request.json().catch(() => null)) as { key?: unknown } | null;
const key = typeof body?.key === "string" ? body.key : "";
if (!key.startsWith(userPrefix(userId)) || key.includes("..")) {
return Response.json({ error: "Unknown upload." }, { status: 400 });
}
try {
const info = await getObjectInfo(key);
if (!info) return Response.json({ error: "The file did not arrive. Please try again." }, { status: 404 });
if (info.size > MAX_UPLOAD_BYTES || !ALLOWED_TYPES.has(info.type)) {
await deleteObject(key);
return Response.json({ error: "That file is not allowed." }, { status: 422 });
}
// Save the key somewhere, for example a "files" table in Postgres,
// so you can list the user's files later.
return Response.json({ key, size: info.size });
} catch (err) {
console.error("Could not check upload", err);
return Response.json({ error: "Could not finish the upload." }, { status: 500 });
}
}The bucket is private, so a plain link to a file does not work. To download, sign a GET URL on the server and redirect to it. The link expires after five minutes, so a shared or leaked link stops working soon.
import { getUserId } from "@/lib/auth";
import { createDownloadUrl } from "@/lib/s3";
import { userPrefix } from "@/lib/uploads";
export async function GET(request: Request) {
const userId = await getUserId();
if (!userId) return new Response("Please sign in.", { status: 401 });
const key = new URL(request.url).searchParams.get("key") ?? "";
if (!key.startsWith(userPrefix(userId)) || key.includes("..")) {
return new Response("Not found", { status: 404 });
}
try {
const url = await createDownloadUrl(key, key.split("/").pop());
return Response.redirect(url, 302);
} catch (err) {
console.error("Could not sign download", err);
return new Response("Could not create a download link.", { status: 500 });
}
}To show an image or PDF inline instead of saving it, leave out the download name. Then the browser opens the file with the content type it was uploaded with.
Step 6: Allow your domain and fix the CORS error
Browsers only send a cross-site PUT when the bucket's CORS rule names your site. On CloudHike you don't write CORS JSON. Instead, go to Storage → Settings → Allowed upload domains, add your app's address and click Save. The bucket is updated within a few seconds.
- Development and preview environments already allow
http://localhost:*andhttp://127.0.0.1:*, sonpm run devworks on any port. - Production allows only the sites you list. Add your real origin, such as
https://app.example.com, before you launch. - Enter an origin with no path. One
*works for subdomains, such ashttps://*.example.com. - This only changes CORS. The bucket stays private, and every upload and download still needs a presigned URL.
The Storage docs have the full rules. When an upload fails, open the browser's dev tools, then check the Console and Network tabs:
| What you see | Why | Fix |
|---|---|---|
No 'Access-Control-Allow-Origin' header or Failed to fetch | The page's origin is not in Allowed upload domains for that environment | Add the exact origin (scheme, host and port) and save |
403 with SignatureDoesNotMatch | The content-type header differs from the one you signed, or the URL was changed | Send file.type as content-type, and pass the URL through untouched |
403 with Request has expired | The URL is older than expiresIn | Ask for a new URL right before each upload |
400 or 403 mentioning a checksum | The SDK signed a checksum for an empty body | Set requestChecksumCalculation: "WHEN_REQUIRED" on the client |
| Works locally, fails in production | Production allows only listed sites, and each environment has its own list | Add the production origin under the production environment |
Production checklist
- Add the five
S3_*variables to your host's environment variables (Vercel: Project → Settings → Environment Variables). - Add your production origin under Allowed upload domains for the production environment.
- Keep upload URLs short-lived (a minute is plenty) and sign them right before use.
- Check every upload after it lands, and delete files that break your rules.
- Save keys in your database with the owner, and check ownership before you sign a download.
- Limit how often one user can ask for upload URLs with a Redis rate limit.
- Watch the space used on the Storage page. Plan limits and prices are on the pricing page.
Frequently asked questions
Why use presigned URLs instead of uploading files through my Next.js server?
The file goes straight from the browser to storage, so it never counts against Server Action or serverless body size limits, and your server does not pay for the bandwidth or the time. Your server still decides who may upload what, because it signs every URL.
How do I limit the file size of a presigned S3 PUT upload?
A presigned PUT URL cannot enforce a size. Check the size the browser reports before you sign, then check the real size with HeadObject after the upload and delete the file if it is too big. S3 also has presigned POST policies with a size range, but this guide uses PUT because it is simpler.
How do I fix the CORS error when uploading to S3 from the browser?
The bucket must allow your page's origin. On CloudHike, add your site under Storage, Settings, Allowed upload domains for the right environment. Localhost is already allowed in development, so an error that only happens in production usually means the production origin is missing.
How long should a presigned URL be valid?
As short as works. For uploads, sign right before the PUT and use about a minute. For downloads, a few minutes to an hour is common. Anyone who has the URL can use it until it expires, so shorter is safer.
Can I make the files in my bucket public?
CloudHike buckets are private. Share files with presigned GET URLs, which expire, or stream them through your own route handler if you need permanent links or access checks on every view.
Does this code work with AWS S3 or other S3-compatible storage?
Yes. The AWS SDK v3 works with any S3-compatible service. Change the endpoint, region and keys. Keep forcePathStyle for services that expect the bucket name in the path.
