Sanic-CORS

2.2.0 · active · verified Thu Apr 16

Sanic-CORS is a Sanic extension that provides Cross-Origin Resource Sharing (CORS) support, primarily through a decorator. It is based on the popular Flask-CORS library. The current version is 2.2.0, with a release cadence that aligns with critical Sanic updates and bug fixes, typically every few months for major Sanic version compatibility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to enable CORS globally for a Sanic application using `CORS(app)` and how to apply it to individual routes using the `@cross_origin()` decorator. It sets up a basic Sanic app with two routes and ensures CORS headers are correctly handled for preflight OPTIONS requests and actual data requests.

from sanic import Sanic, response
from sanic_cors import CORS, cross_origin
import os

app = Sanic(__name__)

# Enable CORS for the entire application (or specify options)
CORS(app, origins="*", allow_headers="*", expose_headers="*", automatic_options=True)

@app.route("/", methods=["GET"])
@cross_origin(origins=os.environ.get('ALLOWED_ORIGIN', '*')) # Decorator for specific route
async def hello_world(request):
    return response.json({"message": "Hello from Sanic-CORS!"})

@app.route("/data", methods=["GET", "POST"])
# cross_origin() can be omitted if CORS(app) handles it globally
async def get_data(request):
    if request.method == "GET":
        return response.json({"data": "Some public data"})
    elif request.method == "POST":
        return response.json({"status": "Data received"})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

view raw JSON →