'Intermittent CORS issue with FastAPI deployed on Heroku

I deployed a FastAPI based backend on Heroku and whenever I query the url via cURL or Postman, it works fine. However, when it queried from a chrome extension (built on React for Github), it throws

Access to fetch at '<API>' (redirected from '<API>') from origin 'https://github.com' has been blocked by CORS policy: 'No-Access-Control-Allow-Origin' header is present on the requested resource.

Funny thing is that the request runs fine for most of the time but when the server is not queried for about 10 mins, it first throws this error 2-3 times then the subsequent requests succeed.

From the frontend, Javascript fetch API is used to query the API with method & Content-type header. To set up CORS policy on backend, I followed this CORS docs. Following is the snippet:

app = FastAPI()

origins = [
  "https://github.com",
  "http://localhost:8000"     # dev
]

app.add_middleware(
  CORSMiddleware,
  allow_origins=origins,
  allow_credentials=True,
  allow_methods=["*"],
  allow_headers=["*"],
)

I am not able to understand if this issue is from frontend, backend or Heroku free dyno going to sleep. Thanks.



Solution 1:[1]

The request to your API is most likely coming from "Origin": "chrome-extension://..."

You can change your FastApi controller to origins = ["*"]

That should give you a temporary fix.

As far as adding your specific Chrome extension to the allowed origins ...that's what I'm on here searching for lol.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 joe