How do you configure CORS to expose custom response headers to client-side JavaScript using Access-Control-Expose-Headers?
Short answer
By default, JavaScript running in the browser can only read a small set of 'safe-listed' response headers (like Content-Type, Content-Length) from a cross-origin response -- any custom headers your API returns (like X-Total-Count for pagination) are invisible to client JS unless…
Advertisement
AModel answer
By default, JavaScript running in the browser can only read a small set of 'safe-listed' response headers (like Content-Type, Content-Length) from a cross-origin response -- any custom headers your API returns (like X-Total-Count for pagination) are invisible to client JS unless explicitly exposed via WithExposedHeaders() in the CORS policy, which adds them to the Access-Control-Expose-Headers response header.
builder.Services.AddCors(options => {
options.AddPolicy("MyPolicy", policy => {
policy.WithOrigins("https://app.mycompany.com")
.WithExposedHeaders("X-Total-Count", "X-Page-Number");
});
});
// Now client JS can read: response.headers.get('X-Total-Count')Real-world example
A paginated API returning results with a custom X-Total-Count header initially confused frontend developers who saw the header in browser dev tools' network tab but couldn't read it via fetch() in JavaScript -- resolved by adding it to WithExposedHeaders.
Likely follow-ups
- Why are only a small set of headers readable by default without this configuration?
- How does this differ for same-origin requests, which have no such restriction?
Related topics