Learning objectives
After reading this article you will be able to:
- Understand why a direct upload triggers a preflight and who has to answer it
- Configure CORS on an S3 bucket for PUT uploads through presigned URLs
- Test the preflight and the upload with curl and tell CORS apart from a signature error
You followed the recommended upload pattern: the backend generates a presigned URL and the browser sends the file straight to storage, without going through your server. In the terminal, a curl with the same URL works. In the browser, the console turns red and the upload never starts.
The problem is almost never in your upload code. It is in a conversation the browser has with the storage before the upload, the preflight. Knowing who takes part in that conversation fixes the error and saves you hours of configuring CORS in the wrong place.
What does the error look like?#
In Chrome, the console message has this shape (the URL is shortened here):
Access to fetch at 'https://my-bucket.s3.us-east-1.amazonaws.com/uploads/photo.jpg?X-Amz-Algorithm=...' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.The end of the message changes with the rule that failed:
Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.| Part of the message | What the storage's answer is missing |
|---|---|
No 'Access-Control-Allow-Origin' header |
A CORS rule that matches your origin |
not allowed by Access-Control-Allow-Headers |
The named header in the list of allowed headers |
Method PUT is not allowed |
PUT in the list of allowed methods |
does not have HTTP ok status |
A 2xx status on the OPTIONS (no rule, a rule that does not match or the wrong endpoint) |
In your JavaScript, fetch rejects with a generic TypeError (Failed to fetch in Chrome) and no status. That is on purpose: for security, the browser does not hand the details of a CORS failure to your code, and the only place they show up is the console. In the Network tab, you see an OPTIONS request to the storage, with status 403 or without Access-Control-* headers. On Amazon S3, that response body says CORS is not enabled for this bucket (the bucket has no CORS rule) or This CORS request is not allowed (there is a rule, but the origin, method or header does not match).
For the general explanation of the mechanism, outside the storage context, see CORS errors explained.
Why does the browser send a preflight?#
A preflight is an OPTIONS request the browser sends on its own, before a cross-origin request that is not "simple", to ask the server whether that request is allowed.
Your page has an origin (scheme, host and port, such as https://app.example.com) and the storage has another. A request made from JavaScript to another origin can only have its response read if the target server allows it, through CORS headers.
Some requests are "simple" and go straight out: GET, HEAD or POST, with safelisted headers only, and a Content-Type of application/x-www-form-urlencoded, multipart/form-data or text/plain. A PUT is never simple. Before it, the preflight goes out:
OPTIONS /uploads/photo.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&... HTTP/1.1
Host: my-bucket.s3.us-east-1.amazonaws.com
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-typeThe storage has to answer with a 2xx status and headers that cover the origin, the method and every requested header:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: PUT
Access-Control-Allow-Headers: content-type
Access-Control-Max-Age: 3000Only then does the PUT with the file go out. The PUT response itself also needs Access-Control-Allow-Origin; without it, the file may well have been stored, but fetch rejects and your code thinks it failed. Access-Control-Max-Age tells the browser how many seconds it may keep the preflight answer (each browser applies its own cap), so the next upload skips the extra round trip.
Why does the bucket, not your API, have to answer?#
CORS is checked against the server that receives the request. The PUT goes to the storage's domain, so the storage is what has to answer the preflight. Adding app.use(cors()) to your API's Express app changes nothing in that conversation, because the API is not part of it.
Your API comes in at another moment: the route that generates the presigned URL. If the page and the API live on different origins, that route needs CORS too, and it is a separate preflight. These are two independent configurations, one on each server.
There is a shortcut: send the file to your API and let it forward it to storage. It works without CORS on the bucket, but the file goes back to using your server's bandwidth and memory, which is exactly what the presigned URL was avoiding.
How do you configure CORS on an S3 bucket?#
On Amazon S3 and many S3-compatible services, CORS is a document of rules attached to the bucket. This one allows uploads from your site and from the dev server:
{
"CORSRules": [
{
"AllowedOrigins": ["https://app.example.com", "http://localhost:5173"],
"AllowedMethods": ["PUT", "GET", "HEAD"],
"AllowedHeaders": ["content-type"],
"ExposeHeaders": ["ETag"],
"MaxAgeSeconds": 3000
}
]
}aws s3api put-bucket-cors --bucket my-bucket --cors-configuration file://cors.json
aws s3api get-bucket-cors --bucket my-bucketOn an S3-compatible service, add --endpoint-url. Some providers do not expose this API and configure CORS another way, or ship a fixed policy; check your provider's docs.
The details that break most often:
- Exact origin. Scheme, host and port, with no trailing slash and no path.
http://localhost:5173andhttp://127.0.0.1:5173are different origins, andhttps://app.example.com/with a slash does not match. - Every requested header. Each name in
Access-Control-Request-Headershas to match an entry inAllowedHeaders. If you send metadata such asx-amz-meta-user, list it, or usex-amz-*(each entry accepts one wildcard). - ExposeHeaders. By default, JavaScript can only read a few response headers. A multipart upload from the browser needs to read each part's
ETag, so it has to be inExposeHeaders. - The configuration is replaced whole.
put-bucket-corsswaps the entire document, and S3 uses the first rule that matches the request. - A CDN or proxy in front. It has to forward
Originand theAccess-Control-Request-*headers and include the origin in its cache key, or an answer cached for one origin gets served to another.
Which headers break the signature?#
With the preflight sorted, the PUT can still come back as a 403 SignatureDoesNotMatch. And if that error response lacks CORS headers, the browser shows a CORS error instead of the real one. That is why a CORS error can hide a signature error.
The rule: every header that went into the signature has to arrive with the same value. The classic case is Content-Type. If the backend signed image/jpeg, the browser has to send exactly image/jpeg. Watch out for the AWS SDK v3 for JavaScript: getSignedUrl leaves content-type out of the signature by default, so the browser can store any type. To lock the type, pass signableHeaders with content-type. Let the backend pick the type from an allowlist, sign it and return it, and have the browser repeat the value. Example with Express and the AWS SDK v3 (npm install express @aws-sdk/client-s3 @aws-sdk/s3-request-presigner):
// server.mjs
import { randomUUID } from "node:crypto";
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import express from "express";
const s3 = new S3Client({
region: process.env.S3_REGION,
endpoint: process.env.S3_ENDPOINT, // leave out on AWS
forcePathStyle: process.env.S3_PATH_STYLE === "true",
credentials: {
accessKeyId: process.env.S3_ACCESS_KEY,
secretAccessKey: process.env.S3_SECRET_KEY,
},
});
const TYPES = new Set(["image/jpeg", "image/png", "image/webp"]);
const app = express();
app.use(express.json());
app.use(express.static("public")); // serves the page with the form
app.post("/uploads", async (req, res) => {
const { contentType } = req.body;
if (!TYPES.has(contentType)) {
return res.status(400).json({ error: "file type not allowed" });
}
const key = `uploads/${randomUUID()}`;
const url = await getSignedUrl(
s3,
new PutObjectCommand({
Bucket: process.env.S3_BUCKET,
Key: key,
ContentType: contentType,
}),
// without signableHeaders, SDK v3 leaves content-type out of the signature
{ expiresIn: 300, signableHeaders: new Set(["content-type"]) },
);
res.json({ url, key, contentType });
});
app.listen(process.env.PORT || 3000);In the browser:
async function uploadFile(file) {
const r = await fetch("/uploads", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ contentType: file.type }),
});
if (!r.ok) throw new Error("file type not allowed");
const { url, key, contentType } = await r.json();
const put = await fetch(url, {
method: "PUT",
headers: { "Content-Type": contentType }, // the same value that was signed
body: file,
});
if (!put.ok) throw new Error(`upload failed with status ${put.status}`);
return key; // store the key in your database
}Other usual suspects: x-amz-* headers (metadata, ACL) sent without being signed, a Content-MD5 added by an upload library, and an axios interceptor that adds Authorization to every request. That last one goes to the storage too: it joins the preflight and, if it gets through, the request is refused for carrying two forms of authentication, since the authorization is already in the URL. For the other reasons behind a 403, see S3 AccessDenied and SignatureDoesNotMatch, and for the whole flow, from the form to the bucket, file uploads in Node.js.
How do you test it with curl?#
curl does not enforce CORS, but it lets you imitate the browser and see the raw response. Generate a URL and simulate the preflight:
curl -i -X OPTIONS "$URL" \
-H "Origin: http://localhost:5173" \
-H "Access-Control-Request-Method: PUT" \
-H "Access-Control-Request-Headers: content-type"Look for a 2xx status and an Access-Control-Allow-Origin with your origin. A 403 or missing headers point to the bucket's CORS rule. Then send the file the way the browser would:
curl -i --upload-file photo.jpg \
-H "Content-Type: image/jpeg" \
-H "Origin: http://localhost:5173" \
"$URL"If the upload goes through in curl, the signature is right and the problem is CORS only. If it returns SignatureDoesNotMatch, compare the Content-Type with what was signed. And if the PUT response has no Access-Control-Allow-Origin, the browser will reject the result even though the file was stored.
For large files, the same reasoning applies to each part of a multipart upload, as in how to upload large files. To decide whether the uploaded file should be open or behind a signed link, see public vs private files.
How to do this on Square Cloud#
On Square Cloud Blob Storage, there is no CORS rule to write: a PUT through a presigned URL from the browser is already accepted from any origin, and there is no per-bucket CORS setting. In the server above, set S3_ENDPOINT=https://s3-blob.squarecloud.app, S3_REGION=auto, S3_PATH_STYLE=true and S3_BUCKET to public or private. S3 keys come from an API key in the "S3 access" tab of the dashboard.
Two conditions apply to the PUT: the API key needs write permission and the plan has to be active. If the upload still fails with both met, the curl test above tells a signature error apart from a CORS one. SigV4 presigned URLs last up to 7 days, but for uploads a few minutes is enough.
Each file can be up to 10 GB, and above 100 MB the upload has to be multipart. Folder rules set the maximum size and the allowed extensions, and there is no ingress fee for uploads or egress fee for downloads. See the details on the Blob Storage page.
Blob Storage
S3-compatible object storage with no egress fees
FAQs
Why does the upload work in curl or Postman but fail in the browser?
CORS is a browser rule. curl and Postman send no preflight and do not check the Access-Control-* headers, so the same URL works outside the browser. A curl test proves the URL and the signature are right; CORS still belongs to the storage.
Will configuring CORS on my API fix it?
No. The preflight goes to the storage's domain, which is what receives the PUT, so the headers have to come from the bucket's response. Your API only needs CORS on the route that generates the URL, if the page lives on another origin.
Can I use a wildcard in AllowedOrigins?
Yes. Uploads through presigned URLs do not use cookies, so the wildcard is accepted. Listing only your site's origins is stricter but does not protect the URL, which works outside the browser anyway. A short expiry is what protects it.
Do I need CORS to show a bucket image in an img tag?
No. An img tag or a plain download link does not go through the CORS check. Only reads made from JavaScript, with fetch or XMLHttpRequest, and uses such as drawing the image on a canvas need the headers.
More in Storage
See all 24 articles- What is a presigned (signed) URL?A presigned URL is a temporary link to a private file that works without login or credentials. See how it works, its limits and when to use it.
- What is object storage?Object storage keeps files as objects with a key and metadata, accessed over an HTTP API. See how it works, what it is for and where its limits are.
- What does 'S3-compatible' storage mean?S3 is Amazon's object storage and its API became the industry standard. Learn what S3-compatible means, what differs between providers, and how to connect.
- Uploading large files: multipart and resumable uploadsMultipart upload splits a large file into parts that are sent in parallel and retried on their own. See the Python walkthrough, how to resume, and common mistakes.