CORSMiddleware: Unblocking Your Frontend from Your Backend
CORS is a browser security rule, not a server bug. Use FastAPI's CORSMiddleware to tell browsers which frontends (e.g., localhost:3000) are allowed to fetch data from your API (e.g., localhost:8000).
Why it exists
Browsers enforce a "Same-Origin Policy" by default. This security measure prevents a script on a malicious website from making requests to another website where you might be logged in, like your bank or email. CORS (Cross-Origin Resource Sharing) is the standard mechanism for a server to tell a browser it's safe to relax this policy for specific, trusted origins.
The mental model
Think of your API as a private club and the browser as its bouncer. When your frontend code (a guest) tries to enter, the bouncer asks for its address (its origin). The bouncer then checks a guest list provided by the club owner (your API's CORSMiddleware configuration). If the frontend's origin is on the list, it's allowed in. If not, the bouncer denies entry, and the browser reports a CORS error. The key is that the bouncer (browser) enforces the rule, but the club (server) sets the policy.
How it works
When a frontend on http://localhost:3000 tries to make a request to a backend on http://localhost:8000, the browser first sends a special "preflight" request (HTTP OPTIONS). FastAPI's CORSMiddleware intercepts this. If http://localhost:3000 is in the configured allow_origins list, the middleware responds with permission headers like Access-Control-Allow-Origin. Seeing this, the browser then sends the actual GET or POST request.
When to use it
Use CORSMiddleware any time your API will be accessed by a JavaScript frontend running in a browser that is served from a different origin. This is the standard setup for modern Single-Page Applications (SPAs) built with frameworks like React, Vue, or Angular. Even if the domain is the same (localhost), a different port number makes it a different origin.
When not to use it
You don't need to configure CORS if your API is only used by non-browser clients like mobile apps, other backend services, or command-line scripts. These clients do not enforce the Same-Origin Policy. You also don't need it in a monolithic application where the frontend and API are served from the exact same origin.
One canonical example
In your FastAPI application, you add the middleware and configure it with a list of trusted frontend origins. A typical setup looks like this: origins = ["http://localhost:3000", "https://your-app.com"]. Then you add the middleware to your app instance: app.add_middleware(CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=[""], allow_headers=[""]). This explicitly tells browsers that frontends from those two origins are permitted to make requests.
Interview question
When is it most appropriate to implement FastAPI's CORSMiddleware in a web application?
- a.To secure your API from all types of unauthorized access, including mobile apps and command-line tools.
- b.When your frontend and backend are deployed as a single, monolithic application on the same domain and port.
- c.When a browser-based JavaScript application needs to fetch data from an API hosted on a different origin.Correct
- d.To allow your backend server to make requests to external third-party APIs without security restrictions.
Why? this is the answer
CORSMiddleware is specifically designed for scenarios where a browser-based frontend attempts to access an API from a different origin, as browsers enforce the Same-Origin Policy. It is not needed for non-browser clients or when the frontend and backend share the exact same origin.
Just read this? Test yourself on what you have been reading.
Read the original → fastapi.tiangolo.com
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on fastapi — each one lists the topics its interview covers.
See open roles