CORS (Flask)

CORS (Cross-Origin Resource Sharing) controls whether browsers allow a web page from one origin to call your Flask API on another origin. Flask-CORS adds the response headers that grant that permission.

Flask

By default browsers block JavaScript on https://app.com from reading responses from https://api.com — a security feature called the same-origin policy. CORS is the server's way of opting in, by sending Access-Control-Allow-Origin and related headers.

The Flask-CORS extension sets these headers for you. CORS(app) allows all origins (fine for public APIs in development), or you scope it with CORS(app, resources={'/api/*': {'origins': 'https://app.com'}}) to allow only specific origins and paths in production.

CORS only affects browser-based callers; server-to-server requests ignore it. It is also distinct from authentication — allowing an origin does not authenticate it, so you still need tokens or sessions to protect data.

Syntax

from flask_cors import CORS
CORS(app)

Examples

Python

from flask_cors import CORS

CORS(app, resources={r"/api/*": {"origins": "https://app.example.com"}})
# Browser apps from that origin may now call /api/* endpoints

Learn it in a lesson

See also

Back to the Dictionary