How can I dynamically determine the origin in my Cloudflare Worker to set the `Access-Control-Allow-Origin` header?

Question

Grade: Education Subject: Support
How can I dynamically determine the origin in my Cloudflare Worker to set the `Access-Control-Allow-Origin` header?
Asked by:
115 Viewed 115 Answers

Answer (115)

Best Answer
(320)
You can access the origin of the incoming request using `request.headers.get('origin')`. Then, you can implement logic to validate this origin against a list of allowed origins or a pattern. Be very careful with this approach to avoid security vulnerabilities. Always sanitize and validate the origin before using it.