How do you configure CORS to expose custom response headers (like X-Total-Count for pagination) to client-side JavaScript?
Short answer
By default, JavaScript can only read a small set of 'safe-listed' response headers from a cross-origin response (Content-Type, Content-Length, etc.) -- any custom headers your API returns are invisible to client JS unless explicitly exposed via WithExposedHeaders() in the CORS…
Advertisement
AModel answer
By default, JavaScript can only read a small set of 'safe-listed' response headers from a cross-origin response (Content-Type, Content-Length, etc.) -- any custom headers your API returns 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