Nov 18, 20269 min read

S3 Presigned URLs in Node.js: Direct Uploads and Downloads

How to let browsers upload to and download from a private bucket without streaming files through your API, how to limit size and type, and how to scope URLs to the user who asked for them.

Illustration for S3 Presigned URLs in Node.js: Direct Uploads and Downloads

A presigned URL lets a browser upload a file straight to a private bucket, or download one from it, with a URL your API signs for one object and a few minutes. The file never passes through your Node.js process, which keeps large uploads off your API servers and out of their request timeouts.

The signing call is one line, and what takes thought is everything around it: choosing a key the user cannot pick, keeping expiry short, limiting size and content type (a presigned PUT does neither), checking what landed in the bucket, and making sure a user can only get download URLs for their own files.

This guide starts with a TypeScript upload service in Encore, where the bucket is declared in code and signed URLs come from the bucket object, and then shows the same flow with the AWS SDK v3, including presigned POST for a hard size limit.

Presigned URL approaches at a glance

Encore bucket with signed URLsAWS SDK v3 presigned PUTAWS SDK v3 presigned POST
Signing callbucket.signedUploadUrl(key, { ttl })getSignedUrl(s3, new PutObjectCommand(...))createPresignedPost(s3, { Conditions })
Size limit at uploadNochecked after uploadNochecked after uploadYes, content-length-range
Content type enforcedChecked after uploadWhen content-type is a signed headerWith an eq condition in the policy
Bucket and IAMDeclared in code, provisioned in your AWS or GCP accountYou create themYou create them
Local developmentLocal bucket on disk, real signed URLsReal bucket or an S3 emulatorReal bucket or an S3 emulator
Client requestPUT with the file as the bodyPUT with the file as the bodymultipart/form-data POST with policy fields

How do you create presigned upload URLs with Encore?

Encore

Encore is a backend framework with built-in infrastructure. An object storage bucket is a variable in your code, and the bucket object can sign upload and download URLs for a single key with a TTL in seconds. encore run serves a local bucket from disk with working signed URLs, and a deploy provisions an S3 bucket on AWS or a Cloud Storage bucket on GCP in your own account, and Encore provisions an IAM role for the service.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create files --example=ts/hello-world$ cd files && mkdir uploads

Authenticate the caller

Every key starts with the user ID, so the auth handler has to say who is calling. This one verifies a short-lived HMAC token; swap in your session or JWT check. The signing key is an Encore secret:

// uploads/auth.ts import { createHmac, timingSafeEqual } from "node:crypto"; import { APIError, Gateway, Header } from "encore.dev/api"; import { authHandler } from "encore.dev/auth"; import { secret } from "encore.dev/config"; const tokenKey = secret("TokenHMACKey"); interface AuthParams { authorization: Header<"Authorization">; } interface AuthData { userID: string; } // Verifies "Bearer <user>.<unix-expiry>.<hex hmac>". export const auth = authHandler<AuthParams, AuthData>(async ({ authorization }) => { const [user, exp, sig] = (authorization ?? "").replace(/^Bearer /, "").split("."); if (!user || !exp || !sig || Number(exp) < Date.now() / 1000) { throw APIError.unauthenticated("invalid token"); } const want = createHmac("sha256", tokenKey()).update(`${user}.${exp}`).digest("hex"); if (sig.length !== want.length || !timingSafeEqual(Buffer.from(sig), Buffer.from(want))) { throw APIError.unauthenticated("invalid token"); } return { userID: user }; }); export const gateway = new Gateway({ authHandler: auth });

The auth handler runs before any endpoint marked auth: true, and getAuthData() returns its result inside the endpoint.

Sign, confirm and download

The service has three endpoints. createUpload picks the key on the server, so a user can never overwrite another user's file or choose a path. completeUpload runs after the browser's PUT and checks the object that landed, deleting it if it is too large or the wrong type. downloadUrl checks ownership before it signs anything:

// uploads/uploads.ts import { randomUUID } from "node:crypto"; import { api, APIError } from "encore.dev/api"; import { getAuthData } from "~encore/auth"; import { Bucket } from "encore.dev/storage/objects"; // Private by default: objects are only reachable through signed URLs. export const attachments = new Bucket("attachments", { versioned: false }); const MAX_BYTES = 10 * 1024 * 1024; const ALLOWED = new Set(["application/pdf", "image/png", "image/jpeg"]); interface CreateUploadResponse { key: string; uploadUrl: string; } // Step 1: the browser asks for a URL, then PUTs the file straight to the bucket. export const createUpload = api( { expose: true, auth: true, method: "POST", path: "/uploads" }, async (): Promise<CreateUploadResponse> => { const { userID } = getAuthData()!; const key = `users/${userID}/${randomUUID()}`; const { url } = await attachments.signedUploadUrl(key, { ttl: 300 }); return { key, uploadUrl: url }; }, ); interface CompleteParams { key: string; } interface CompleteResponse { key: string; size: number; contentType: string; } // Step 2: after the PUT, the browser confirms. The server checks what // landed in the bucket, because a signed PUT URL does not limit size or type. export const completeUpload = api( { expose: true, auth: true, method: "POST", path: "/uploads/complete" }, async ({ key }: CompleteParams): Promise<CompleteResponse> => { const { userID } = getAuthData()!; if (!key.startsWith(`users/${userID}/`)) throw APIError.notFound("upload not found"); if (!(await attachments.exists(key))) throw APIError.failedPrecondition("nothing uploaded yet"); const attrs = await attachments.attrs(key); const type = attrs.contentType ?? ""; if (attrs.size > MAX_BYTES || !ALLOWED.has(type)) { await attachments.remove(key); throw APIError.invalidArgument("PDF, PNG or JPEG up to 10 MiB only"); } return { key, size: attrs.size, contentType: type }; }, ); interface DownloadResponse { url: string; } // Downloads get a five-minute signed GET URL, after the ownership check. export const downloadUrl = api( { expose: true, auth: true, method: "GET", path: "/uploads/download" }, async ({ key }: { key: string }): Promise<DownloadResponse> => { const { userID } = getAuthData()!; if (!key.startsWith(`users/${userID}/`) || !(await attachments.exists(key))) { throw APIError.notFound("upload not found"); } const { url } = await attachments.signedDownloadUrl(key, { ttl: 300 }); return { url }; }, );

The browser sends the file with a plain PUT to uploadUrl, then calls completeUpload with the key. Five-minute URLs are long enough for the upload to start and short enough that a leaked URL is of little use. The default TTL is one hour and the maximum is seven days, so set it explicitly.

We ran this app with encore run: a 13-byte PDF uploaded through the signed URL and confirmed with size: 13, a second user calling completeUpload with the same key got not_found, the signed download URL returned the file, and an upload sent as text/html was rejected and removed, so a second confirm returned failed_precondition.

The bucket declaration is also what the deploy reads: Encore creates the bucket in your AWS or GCP account for every environment, so a coding agent that adds a second bucket for invoices adds one line of code instead of a Terraform change.

Best fit: TypeScript APIs that accept user files, such as attachments, receipts or avatars, where you want the bucket and local development to come from the same code.

How do you generate S3 presigned URLs with the AWS SDK?

With the AWS SDK v3 you sign with getSignedUrl from @aws-sdk/s3-request-presigner for a PUT or GET, and with createPresignedPost from @aws-sdk/s3-presigned-post when you need S3 itself to enforce a size range:

// presign/s3.ts import { randomUUID } from "node:crypto"; import { S3Client, PutObjectCommand, GetObjectCommand, HeadObjectCommand } from "@aws-sdk/client-s3"; import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; import { createPresignedPost } from "@aws-sdk/s3-presigned-post"; const s3 = new S3Client({ region: process.env.AWS_REGION }); const Bucket = process.env.UPLOAD_BUCKET!; const MAX_BYTES = 10 * 1024 * 1024; // Presigned PUT: simple, but S3 accepts any body size the client sends. export async function presignPut(userId: string, contentType: string) { const Key = `users/${userId}/${randomUUID()}`; const url = await getSignedUrl( s3, new PutObjectCommand({ Bucket, Key, ContentType: contentType }), // Sign Content-Type so S3 rejects a PUT that sends a different type. { expiresIn: 300, signableHeaders: new Set(["content-type"]) }, ); return { key: Key, url }; } // Presigned POST: the policy makes S3 reject bodies outside the size range. export async function presignPost(userId: string, contentType: string) { const Key = `users/${userId}/${randomUUID()}`; const { url, fields } = await createPresignedPost(s3, { Bucket, Key, Conditions: [ ["content-length-range", 1, MAX_BYTES], ["eq", "$Content-Type", contentType], ], Fields: { "Content-Type": contentType }, Expires: 300, }); return { key: Key, url, fields }; } export async function presignGet(userId: string, key: string) { const prefix = `users/${userId}/`; if (!key.startsWith(prefix) || key.includes("..")) { throw new Error("key is not owned by this user"); } return getSignedUrl(s3, new GetObjectCommand({ Bucket, Key: key }), { expiresIn: 300 }); } export async function uploadedSize(key: string): Promise<number | undefined> { const head = await s3.send(new HeadObjectCommand({ Bucket, Key: key })); return head.ContentLength; }

By default the presigner signs only the host header, so ContentType in the command does not bind the client to anything. Passing signableHeaders with content-type adds it to X-Amz-SignedHeaders, and S3 then rejects a PUT whose Content-Type differs. Nothing in a PUT URL limits the body size. A presigned POST carries a policy document with conditions, and S3 refuses any upload outside content-length-range before it is stored. The browser sends it as a form, with the policy fields first and the file last:

// presign/client.ts (browser) export async function uploadWithPost(file: File, url: string, fields: Record<string, string>) { const form = new FormData(); for (const [k, v] of Object.entries(fields)) form.append(k, v); form.append("file", file); // the file must be the last field const res = await fetch(url, { method: "POST", body: form }); if (!res.ok) throw new Error(`upload failed: ${res.status}`); }

Three details catch people out. The URL is only as valid as the credentials that signed it, so a URL signed with an ECS task role or other temporary credentials stops working when the session expires, even if expiresIn is longer. Browser uploads need a CORS rule on the bucket that allows your origin and the method. And HeadObject after upload is still worth doing for PUT uploads, since it is the only size check you get.

The bucket, its CORS rule, the IAM policy for the task role, a local stand-in for S3 and the cleanup of abandoned keys are yours to set up and keep in step across environments.

Best fit: Node.js services already on AWS with their own bucket and IAM setup, and any upload that must be size-limited by S3 itself.

How to choose

Use presigned POST when an oversized upload must never reach the bucket, for example on a public form. Use presigned PUT, from Encore or the SDK, when users are authenticated and a check after upload is enough, and keep the key server-chosen and the TTL short in either case. Pick Encore when you want the bucket, its permissions and a working local bucket to come from the TypeScript code that signs the URLs, deployed to your own AWS or GCP account.

Frequently asked questions

How do I generate a presigned URL for S3 in Node.js?

With the AWS SDK v3, build a PutObjectCommand or GetObjectCommand for the bucket and key, then pass it to getSignedUrl from @aws-sdk/s3-request-presigner with expiresIn in seconds. The URL is signed with the credentials of the process that created it and is valid for that one key until it expires.

Can a presigned PUT URL limit the file size?

No. A presigned PUT URL fixes the bucket, key and any signed headers, but S3 accepts whatever body size the client sends up to the 5 GB single-PUT limit. To cap the size before the upload lands, use a presigned POST with a content-length-range condition, or check the object size after upload and delete objects that are too large.

How long should a presigned URL be valid?

As short as the client flow allows, usually a few minutes. Anyone who has the URL can use it until it expires. A URL signed with temporary credentials, such as an ECS task role, also stops working when those credentials expire, even if expiresIn is longer.

Do browser uploads to S3 need CORS?

Yes. A browser PUT or POST to a bucket on another origin needs a CORS rule on the bucket that allows your site's origin and the method. Without it the browser blocks the request even though the signature is valid.

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.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders