How does CORS prevent XSS?

TL;DR: How does CORS prevent XSS? It does not. It is not meant to do so.

CORS is intended to allow resource hosts (any service that makes its data available via HTTP) to restrict which websites may access that data.

Example: You are hosting a website that shows traffic data and you are using AJAX requests on your website. If SOP and CORS were not there, any other website could show your traffic data by simply AJAXing to your endpoints; anyone could easily "steal" your data and thus your users and your money.

In some cases that sharing of data (Cross Origin Resource Sharing) is intended, e.g. when displaying likes and stuff from the Facebook API on your webpage. Simply removing SOP to accomplish that is a bad idea because of the reasons explained in the above paragraph. So CORS was introduced.

CORS is unrelated to XSS because any attacker who can place an evil piece of JavaScript into a website can also set up a server that sends correct CORS headers. CORS cannot prevent malicious JavaScript from sending session ids and permlogin cookies back to the attacker.


Cross-Site-Scripting (XSS) is the execution of attacker defined script code in the context of another site. CORS does not prevent XSS, in fact it is unrelated to XSS.

Instead CORS offers a way to weaken existing restrictions on Ajax requests (i.e. XMLHTTPRequest) in a way which hopefully does not introduce more security problems. Traditionally XMLHTTPRequest was restricted to communicate within the same origin, that is it was not possible to sent a request to some external site. This restriction was done so that an attacker cannot do a cross site request and get the result of the request back, because this would allow an attacker to read data from sites where the users was logged in (because session and other cookies are sent with each request to a site).

With CORS this restriction is partly removed. It is now possible to sent an XMLHTTPRequest to another site but the result can only read inside the application if the remote site explicitly added some CORS headers which allow the access. But again, this is not executing script on the remote site and thus this is unrelated to XSS.


CORS does not protect anything, SOP (Same Origin Policy) protects something instead. SOP protects the target domain and the browser user.

In fact, CORS weaken existing restrictions of SOP to help website developers to use shared data from other origins.