Presigned URLs for S3 uploads
How to generate a short-lived S3 PUT URL in Node.js so the browser uploads the file directly. Also CORS, matching signed headers, and why the URL is a secret.
This post is about presigned URLs for Amazon S3 uploads. A presigned URL is a web address that lets a browser send a file straight to S3 for a short time. Your API creates that URL. It does not receive the file.
Sunday Pantry is a small recipe website. Each recipe can have a cover photo. In an earlier post, a Fastify route read the whole photo into the API process, then called PutObject. That works. It also means every byte travels through your server. You use memory. You can hit timeouts. You pay for bandwidth twice: client to API, then API to S3.
A presigned URL changes that path. The browser uploads with HTTP PUT to S3. Your API only generates a URL that expires in five minutes. After this guide you will know getSignedUrl with PutObjectCommand, what to return to the client, and why the URL is a bearer token.
A bearer token is a secret carried in the request itself. Anyone who has the URL can upload to that object key until the URL expires. The person uploading does not need their own AWS login.
What a presigned URL is
Amazon S3 is object storage. You put files in a bucket under a key, which is the object’s path and name.
Anyone with valid AWS credentials can create a presigned URL. For the client upload to succeed, the AWS identity that signed the URL must be allowed to perform PutObject on that key. IAM (Identity and Access Management) is the AWS system that grants that permission.
The URL carries:
- Bucket and object key
- HTTP method (
PUTfor upload) - An expiration
The browser, or any HTTP client, sends the file to that URL. S3 checks a cryptographic signature in the URL and checks the clock. No IAM user is attached to the person uploading the photo.
If an object already exists at that key, a successful PUT replaces it, unless you add conditional writes. Include a unique coverId in the key so two recipes do not overwrite each other.
You can use the same URL more than once until it expires. Treat it like a secret. Anyone who has it can upload to that key.
Credentials bound the lifetime. If you signed with temporary role credentials, the URL dies when the session dies, even if you asked for a longer expiresIn. IAM user signatures can last up to 7 days with Signature Version 4, which is the AWS signing scheme S3 uses here. For a cover upload, 5 minutes is plenty.
A small example
The API accepts a filename, builds a key, and returns the URL plus ids. Five minutes (expiresIn: 300) matches a form the person submits right away.
import { randomUUID } from "node:crypto";
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const s3 = new S3Client({ region: "us-east-1" });
const ORIGINALS_BUCKET = "pantry-covers-originals";
const mintCoverUpload = async (filename: string) => {
const coverId = randomUUID();
const key = `${coverId}/${filename}`;
const command = new PutObjectCommand({
Bucket: ORIGINALS_BUCKET,
Key: key,
});
const uploadUrl = await getSignedUrl(s3, command, {
expiresIn: 300,
});
return { coverId, key, uploadUrl };
};Walk through that function. randomUUID creates a unique coverId so each upload gets its own prefix. The key is coverId plus the filename, for example 9f3a/sunday-soup.jpg. PutObjectCommand names the bucket and key. It does not send the file. getSignedUrl turns that command into a URL that is valid for 300 seconds. The return value is three fields the client needs: the id, the key, and the URL.
A small HTTP handler:
app.post("/covers/upload-url", async (request, reply) => {
const { filename } = request.body as { filename?: string };
if (!filename) {
return reply.status(400).send({ error: "filename is required" });
}
const payload = await mintCoverUpload(filename);
return reply.send(payload);
});This route does not accept a file. It reads a filename from the JSON body. If the filename is missing, it returns HTTP 400. If the filename is present, it returns { coverId, key, uploadUrl }. Status 200 is correct here. Nothing is stored in S3 yet.
The client then sends the bytes with PUT. Content-Type on that PUT should match what you intend to store. If you sign extra headers, the browser must send those exact headers or S3 returns SignatureDoesNotMatch. That error means the request the browser sent is not the request the URL was signed for.
const putCoverFromBrowser = async (
uploadUrl: string,
file: File,
) => {
const response = await fetch(uploadUrl, {
method: "PUT",
body: file,
headers: {
"Content-Type": file.type,
},
});
if (!response.ok) {
throw new Error(`S3 upload failed: ${response.status}`);
}
};This function takes the URL from your API and a File from an <input type="file">. fetch uses method PUT and sends the file as the body. It also sends Content-Type from file.type, such as image/jpeg. If S3 responds with an error status, the function throws.
If you did not include ContentType on the PutObjectCommand when signing, adding that header on the client can break the signature. Keep the signed request and the real request the same. Many apps set content type on the command so it is part of the signature, then send the same header.
To try this against a local emulator, use the same S3Client endpoint settings as in the first post. Path-style addressing (forcePathStyle: true) is common there. Path-style means the bucket name is in the URL path, not in the hostname.
How it works
Your API never holds the photo. It only proves to S3 that a trusted identity allowed one PUT to one key for a short window.
The browser talks to S3, not to your API. That is why CORS matters. CORS (Cross-Origin Resource Sharing) is a browser rule. A page on https://sundaypantry.example may not call https://pantry-covers-originals.s3.amazonaws.com unless the bucket says that origin is allowed.
The bucket needs a CORS rule that allows the site origin, PUT, and the headers you actually send (Content-Type at minimum). Without it, the URL route returns 200 and the PUT dies in the browser as a CORS error that looks like a network failure.
A tight rule names your origin, PUT and HEAD, and a short MaxAgeSeconds. HEAD is often used when the browser checks the object. A wildcard origin (*) is how any website can use a leaked URL from another tab. Prefer the real Sunday Pantry origin.
Preflight (OPTIONS) must succeed before the PUT. A preflight is an extra request the browser sends to ask “is this cross-origin PUT allowed?” If you signed extra headers, list them in AllowedHeaders. A mismatch here is as common as a signature mismatch.
S3 checks the signature when the PUT arrives. A download that started immediately before expiry can finish after expiry. A retry after expiry fails. Plan the client so a slow network does not sit on a URL until it is dead, then retry the same URL.
The URL is only as powerful as the signer. If the role cannot s3:PutObject on that key, the uploader gets 403 even with a well-formed URL. HTTP 403 means access denied. Bucket policies that Deny the object also win.
Clock skew on the machine that signs can produce SignatureDoesNotMatch. Clock skew means the server’s clock is wrong. Sync time with NTP on servers that create URLs. NTP (Network Time Protocol) keeps machine clocks close to real time.
Corporate proxies that rewrite query strings also break signatures. The signature covers the query string. If a proxy adds or reorders parameters, S3 sees a different request. Test without the proxy if you see mismatches.
Presigned URLs are bearer tokens. Anyone who intercepts them can upload until they expire.
Put these limits on every URL you create:
- Short expiry. 300 seconds for an in-page upload. Not 7 days.
- Exact key. The signer chooses
coverId/filename. The client cannot pick another key with that URL. - Method. A
PUTURL does not grantGET. Create a separateGETURL if the person needs to preview from S3. - Network conditions (optional). IAM
aws:SourceIpon the principal or bucket can require thePUTto come from a known range. That also affects every other S3 call from that principal.
Do not put the URL in server logs. Do not put it in a public GitHub gist. The API response is already enough exposure. HTTPS on the URL endpoint matters, because the response contains the secret.
After a successful PUT, the original sits in pantry-covers-originals. Nothing has resized yet. Virus scan, dimension checks, and Sharp cannot run in this API process until you read the object back from S3, or run them in a worker after the PUT. The next post starts that worker from an S3 event.
Common mistakes
Signing with a role that cannot PutObject. The URL call succeeds. The browser PUT fails. Check the role, not the React code first. Creating a URL only needs permission to sign. Using the URL needs s3:PutObject on that key.
Mismatching headers. You signed Content-Type: image/jpeg. The client sends image/png. The signature fails. Align the command you sign with the headers you send.
No CORS on the bucket. The URL route works. The browser PUT never leaves the origin check. Add a rule for your site origin before you debug signatures.
Trusting filename without sanitizing the key. ../../other-prefix/secret is a bad key. Allow a safe basename. Keep coverId as the first prefix you control. A basename is the file name without path segments.
Long-lived URLs on Lambda. The URL dies with the execution role’s session if that session is shorter than expiresIn. Lambda often uses temporary credentials. A five-minute URL is safer than a one-hour URL for that reason too.
Assuming the API still has the bytes. It does not. You cannot inspect pixels in this process until S3 has the object.
Returning 202 from the URL route. Nothing has been stored yet. 200 with { coverId, key, uploadUrl } is accurate. Status stored belongs after the PUT succeeds, from a client callback or from an S3 event.
When you do not need this
If you must inspect bytes before they land in the bucket, keep the multipart route on your API. Examples: a malware scan on a box you trust, rewriting EXIF, rejecting huge camera dumps. You pay the extra hop on purpose.
If the files are tiny and the API already sits next to the bucket in the same region, the hop is cheap. Presigning still helps browsers on slow uplinks: they talk to S3, not to a small Node process.
If the client is a trusted backend that already has AWS credentials, it can call PutObject itself. A presigned URL is for a browser or other client that must not hold those credentials.
Further reading
- Download and upload objects with presigned URLs – who can sign, expiry, and bearer-token limits
- Previous: Claiming a job in DynamoDB
- Next: S3 event notifications to SQS
Related posts
- Two AWS designs for an image pipeline
A comparison of a Node.js worker you run yourself and a setup with presigned uploads plus Lambda. What each design includes, and how to choose.
- Processing SQS messages with Lambda
How Lambda receives messages from SQS, parses the nested S3 event, resizes the image, and writes to another bucket. Also batches, timeouts, and Sharp on Amazon Linux.
- S3 event notifications to SQS
How an S3 ObjectCreated event can put a message on SQS. Covers the queue access policy, decoding object keys, and writing processed files to a different bucket.