How S3 presigned POST works, the policy conditions that cap file size and restrict content type, generating one with the AWS SDK for JavaScript v3, uploading from the browser with FormData, the CORS and error cases, and how to enforce the same limits with signed upload URLs in an Encore service.

Browser uploads straight to S3 keep large files off your API servers, and the usual tool is a presigned PUT URL. That URL lets the holder upload anything to the key until it expires, so a profile photo endpoint can end up storing a 4 GB video.
A presigned POST signs a policy with size and type conditions that S3 enforces. This guide covers the conditions, Node.js code, the browser side and the errors.
The POST policy docs describe the conditions S3 can enforce. Your server builds the policy and signs it with its own credentials, the client sends the signed fields with the file, and S3 checks every condition before it stores anything.
The @aws-sdk/s3-presigned-post package builds and signs the policy with an S3 client from @aws-sdk/client-s3:
Create the presigned POST on the server:
// presign.ts
import { S3Client } from "@aws-sdk/client-s3";
import { createPresignedPost } from "@aws-sdk/s3-presigned-post";
import { randomUUID } from "node:crypto";
const s3 = new S3Client({ region: "eu-central-1" });
const BUCKET = "acme-avatars";
const MAX_BYTES = 5 * 1024 * 1024;
const TYPES = new Set(["image/png", "image/jpeg", "image/webp"]);
export async function presignAvatarUpload(userID: string, contentType: string) {
if (!TYPES.has(contentType)) {
throw new Error("unsupported content type");
}
const key = `avatars/${userID}/${randomUUID()}`;
const { url, fields } = await createPresignedPost(s3, {
Bucket: BUCKET,
Key: key,
Conditions: [
["content-length-range", 1, MAX_BYTES],
["eq", "$Content-Type", contentType],
],
Fields: { "Content-Type": contentType },
Expires: 300,
});
return { url, fields, key };
}
The Key is fixed and generated on the server, so a client cannot overwrite another user's file, and the eq condition pins the content type the client declared to one value from the allow list. Expires is in seconds, with a default of one hour, and five minutes is plenty for a form that uploads right away. Use ["starts-with", "$key", "uploads/user-123/"] instead of a fixed Key only when the client must choose file names, and validate them again after upload.
The signature uses whatever credentials the S3 client resolves, so on ECS or Lambda the task or function role needs s3:PutObject on arn:aws:s3:::acme-avatars/avatars/*. A POST signed with temporary credentials also stops working when they expire, even if the policy's own expiry is later.
The browser sends a multipart/form-data request to the returned url with every field from fields and the file last. S3 ignores form fields after the file, so a different order breaks the signature check:
// upload.ts (browser)
export async function uploadAvatar(file: File) {
const res = await fetch("/api/avatars/presign", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ contentType: file.type }),
});
const { url, fields, key } = await res.json();
const form = new FormData();
for (const [name, value] of Object.entries(fields as Record<string, string>)) {
form.append(name, value);
}
form.append("file", file);
const upload = await fetch(url, { method: "POST", body: form });
if (upload.status !== 204) {
throw new Error(`upload failed: ${upload.status} ${await upload.text()}`);
}
return key;
}
On success S3 returns 204 No Content by default, or 201 with an XML body if the policy sets success_action_status. Do not set the Content-Type header on the fetch yourself, since the browser has to add the multipart boundary. The bucket needs a CORS rule that allows POST from your origin, or the browser blocks the request before it reaches S3.
S3 answers a rejected POST with an XML error document, and the code says which condition failed:
The conditions only cover what the client declares about the upload. A file named avatar.png with Content-Type: image/png can still contain anything, so check the bytes when they matter, for example by reading the image header in an S3 event notification handler and deleting files that fail.
A presigned PUT URL is simpler for clients, since the file is the request body with no form encoding, and it works well for trusted clients such as your own mobile app or a backend job. It is also what most SDK helpers and storage abstractions generate by default. The presigned URL guide for Node.js covers that path. Reach for POST when the client is a browser you do not control and the size or type limit has to hold before the bytes are stored.
Encore brings infrastructure from code, so the bucket is declared in the service, and on deploy Encore provisions it in S3 with an IAM role for the service. Its signed upload URLs are presigned PUT URLs with a time limit and no size conditions, so the service enforces the limits in a confirm step: the client uploads, then calls an endpoint that checks the stored object's size and content type and deletes it if either is wrong.

Run in your terminal to get started locally.
Declare the service:
// avatars/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("avatars");
Track each upload in a table:
-- avatars/migrations/1_avatars.up.sql
CREATE TABLE avatar_uploads (
object_key TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
content_type TEXT NOT NULL,
confirmed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
Then the endpoints that issue the upload URL and confirm the upload:
// avatars/avatars.ts
import { api, APIError } from "encore.dev/api";
import { Bucket } from "encore.dev/storage/objects";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { getAuthData } from "~encore/auth";
import { randomUUID } from "node:crypto";
const avatars = new Bucket("avatars");
const db = new SQLDatabase("avatars", { migrations: "./migrations" });
const MAX_BYTES = 5 * 1024 * 1024;
const TYPES = new Set(["image/png", "image/jpeg", "image/webp"]);
// The owner comes from the auth data, never from the request body.
export const presign = api(
{ expose: true, auth: true, method: "POST", path: "/avatars/presign" },
async (p: { contentType: string }): Promise<{ key: string; url: string }> => {
if (!TYPES.has(p.contentType)) {
throw APIError.invalidArgument("contentType must be png, jpeg or webp");
}
const userID = getAuthData()!.userID;
const key = `avatars/${userID}/${randomUUID()}`;
await db.exec`
INSERT INTO avatar_uploads (object_key, user_id, content_type)
VALUES (${key}, ${userID}, ${p.contentType})
`;
const { url } = await avatars.signedUploadUrl(key, { ttl: 300 });
return { key, url };
},
);
export const confirm = api(
{ expose: true, auth: true, method: "POST", path: "/avatars/confirm" },
async (p: { key: string }): Promise<{ ok: boolean }> => {
// Only the uploader can confirm their own key.
const row = await db.queryRow<{ content_type: string; confirmed_at: Date | null }>`
SELECT content_type, confirmed_at FROM avatar_uploads
WHERE object_key = ${p.key} AND user_id = ${getAuthData()!.userID}
`;
if (!row) throw APIError.notFound("unknown upload");
if (row.confirmed_at) return { ok: true };
if (!(await avatars.exists(p.key))) throw APIError.failedPrecondition("file not uploaded yet");
const attrs = await avatars.attrs(p.key);
if (attrs.size > MAX_BYTES || attrs.contentType !== row.content_type) {
await avatars.remove(p.key);
await db.exec`DELETE FROM avatar_uploads WHERE object_key = ${p.key}`;
throw APIError.invalidArgument("file too large or wrong content type");
}
await db.exec`UPDATE avatar_uploads SET confirmed_at = now() WHERE object_key = ${p.key}`;
return { ok: true };
},
);
The client uploads with a plain PUT to the returned URL and a Content-Type header, then calls confirm, and only confirmed rows are ever shown as a user's avatar. An oversized upload still reaches the bucket for a moment, which is the trade-off against a POST policy, and unconfirmed rows older than an hour can be swept by a nightly cron job, which runs on the Encore platform in deployed environments and not locally. encore run starts Postgres locally and stores bucket objects on the local filesystem, so the presign, upload and confirm flow can be tested end to end on a laptop.
An agent changing the limits, for example allowing GIFs or raising the cap, edits the two constants and tests the confirm path locally in the same change.
Best fit: Apps that accept user uploads into their own AWS account and want the bucket, the upload records and the size and type checks in one service.
starts-with prefix.content-length-range and pin or prefix Content-Type.Expires short, five minutes for immediate uploads.POST from your origin in the bucket's CORS rules.A presigned PUT URL signs one request for one key and cannot express a size range, so a client can upload any size up to 5 GB. A presigned POST signs a policy document with conditions, such as content-length-range and a Content-Type prefix, and S3 rejects uploads that break them.
Use a presigned POST with the condition ["content-length-range", 1, 10485760] for a 10 MB cap. S3 checks the body size against the signed policy and returns EntityTooLarge or EntityTooSmall without storing the object.
Install @aws-sdk/client-s3 and @aws-sdk/s3-presigned-post, then call createPresignedPost(client, { Bucket, Key, Conditions, Fields, Expires }). It returns a url and a fields object, and the browser sends those fields plus the file, last, as multipart/form-data to the url.
A form field the policy restricts does not match, such as a Content-Type outside the starts-with prefix or a key outside the allowed path, or the policy has expired. Fields must be sent exactly as returned, and the file field must come after them.
Yes. Declare the bucket in the service, and Encore provisions it in your own AWS account and grants the service access through an IAM role. The service can still call the AWS SDK to mint a presigned POST policy with size and content-type limits.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.