The S3 CORS Rule: Why the Browser Blocks a Presigned Link, and the Four Lines That Let Your Page Read the File
The subtitle viewer asks the backend for a presigned S3 link, then fetches the SRT from S3. The backend already allows localhost:3000, but S3 doesn't, so the browser blocks the second response. An S3 CORS rule with the app's origin, GET and HEAD fixes it, and Celery's five task kinds are summed up at the end.
What you will learn
- Explain what an origin is and why a page can't read a response from another origin
- Follow the SRT viewer's two requests and see which one CORS blocks
- Write an S3 bucket CORS rule with the right origins, methods, headers and max age
- Know when PUT is needed and what to change when the app moves to a new address
Before you start
- Private S3 uploads from FastAPI
The finished project page has two buttons, View SRT and Download SRT. Click View SRT and the subtitles open inside the page: a Cues tab with every cue's number, start and end time and text, and a Raw SRT tab with the plain file. But this viewer only works once S3 allows it. Without that, the file never shows.
Two requests, one blocked
Here's what the viewer does, in lib/api.ts:
async getProjectSrtContent(accessToken: string, id: string): Promise<string> {
const { url } = await request<{ url: string }>(
`/api/v1/projects/${id}/srt`,
{ auth: accessToken },
);
const res = await fetch(url);
if (!res.ok) {
throw new ApiError(res.status, `Failed to fetch SRT body: ${res.statusText}`);
}
return await res.text();
},
The page runs in the browser on localhost port 3000. First it asks the FastAPI backend for a link to the file. The backend already allows localhost:3000 through its CORS middleware, so that call goes through and returns a presigned S3 link. Then the page fetches the file from that link. But the link points to the S3 bucket, which is a different origin.
An origin is the scheme, the host and the port together. For a request like this, the browser looks for one header in the answer, Access-Control-Allow-Origin. By default S3 doesn't send it, so the browser blocks the response and the page never gets the file. This check is CORS, Cross-Origin Resource Sharing. The browser does the checking, and the server, here S3, decides which sites it trusts.
The check in action
A small page on localhost:3000 fetched an SRT file from another origin that sends no CORS header. The page showed "blocked: Failed to fetch", and the console said why:
Access to fetch ... from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Then the other side answered with that header set to http://localhost:3000. The response came back 200 and the page showed the SRT text, cue 1, "Hello and welcome". A request from any other origin still got no header, so only the listed site could read the file. That's exactly what the S3 rule does for the bucket.
Set the rule on the bucket
In the S3 console: Buckets, open the bucket that holds the uploads, the Permissions tab, scroll to Cross-origin resource sharing (CORS), Edit, paste the rule, save changes. The project keeps the same kind of rule in s3_cors_rule.json. Its values, in S3's JSON format:
[
{
"AllowedHeaders": ["*"],
"AllowedMethods": ["GET", "HEAD"],
"AllowedOrigins": ["http://localhost:3000"],
"MaxAgeSeconds": 3000
}
]
- AllowedOrigins: the sites that may read from the bucket. For now, only localhost:3000.
- AllowedMethods: what those sites may do. The viewer only reads, so GET and HEAD are enough. The rule in the console also lists PUT and the origin
http://127.0.0.1:3000; you need PUT only when the browser uploads straight to the bucket. - AllowedHeaders:
*lets the request carry any header. - MaxAgeSeconds: 3000 lets the browser reuse the permission answer for up to fifty minutes.
The browser-to-backend half of the same problem (CORS middleware in FastAPI, or a dev proxy) is in CORS between a React client and FastAPI.
The other half of this lecture: five kinds of Celery task
The same lecture closes the Celery story with the kinds of ticket a worker can take. Each one has its own article:
| Kind | Call | Use it for |
|---|---|---|
| Run it now, in the background | delay | A job too long for a request, like transcription. See Celery and Redis |
| Run once, later | apply_async with countdown or eta | A reminder, a launch, anything that runs once at a set time |
| Run on a schedule | Celery Beat with crontab | A nightly cleanup. See scheduled jobs with Celery Beat |
| Try again when it fails | autoretry_for, retry_backoff, max_retries | Errors that pass, like a network call. See retries and backoff |
| Steps in order | chain of .s() signatures | Download, transcribe, upload. See chain, group and chord |
In the lecture's small project: apply_async with countdown=5 stayed pending at one second and succeeded at 5.1 seconds. A retry with backoff 2 and max retries 3 waited 2, then 4 seconds and succeeded on the third attempt after 6.1 seconds; made to keep failing, it waited 2, 4, then 8 seconds and ended in FAILURE after 14.2 seconds. A chain of three steps passed each result to the next and finished in 1.2 seconds.
Common mistakes
- Fixing the backend's CORS and expecting S3 to follow. They're two servers with two rules.
- Setting AllowedOrigins to
*on a bucket of private files. - Forgetting the new address after deploying, then seeing an empty viewer.
- Adding PUT "just in case". Only allow what the page does.
Quick recap
- The browser blocks a page from reading another origin unless that server says yes.
- The viewer reads the SRT straight from S3, so the bucket needs a CORS rule with the app's origin.
- GET and HEAD for reading; PUT only for browser uploads.
Try it yourself
Remove localhost:3000 from the rule, click View SRT, and read the console error. Then put it back.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.
