-
Notifications
You must be signed in to change notification settings - Fork 353
Description
Description:
Problem Description
Responses from Hugging Face endpoints, including both the main REST APIs and APIs hosted within Spaces, are missing the Access-Control-Max-Age
CORS header.
As a result, browsers are forced to send a preflight OPTIONS
request before every single API call that requires it (e.g., requests with custom headers like Authorization
or non-simple methods/content-types). Since the preflight response cannot be cached by the browser, this leads to unnecessary network round-trips and adds significant latency to every request made from a web application.
Examples
This issue can be observed across the platform. Here are two examples:
-
Hugging Face REST API (e.g., fetching a raw file):
Any request to this endpoint from a browser with custom headers will trigger a preflight check.fetch('https://huggingface.co/datasets/viocha/api-test/raw/main/12.md',{ headers:{Authorization:'Bearer hf_xxxxxxxxxxxxxxx'} })
-
Space Application API:
APOST
request with aContent-Type: application/json
header is a classic case that requires a preflight request. This check is repeated for every subsequent call.fetch('https://viocha-test-cors.hf.space/api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user: 'test-user', action: 'check-cors' }) }) .then(response => response.json()) .then(data => console.log('Data:', data)) .catch(error => console.error('Error:', error));
Current Headers Example
The API correctly returns other essential CORS headers, but the caching directive is missing:
access-control-allow-headers: authorization
access-control-allow-methods: GET
access-control-allow-origin: http://localhost:8080
Suggestion
To improve performance and reduce redundant network traffic, I strongly recommend adding the Access-Control-Max-Age
header to all relevant API responses. This will allow browsers to cache the preflight results for a specified duration.
A reasonable value would be between 1 and 24 hours (e.g., 86400 seconds).
Example of suggested header:
Access-Control-Max-Age: 86400
This simple change would significantly enhance the performance and efficiency of web applications interacting with any Hugging Face API endpoint.