Chapter 15
XHR
XHR is a browser-level API that allows the client to script data transfers via JavaScript. XHR made it’s first debut in IE5, and was created by the original team that built the Outlook Web App. It was one of the key technologies behind the Async JavaScript and XML (AJAX) revolution. Prior to XHR, the webpage had to be refreshed to send any state updates between client and server. With XHR, this workflow could be done async and under full control of the application in JavaScript code. XHR is what enabled us to make the leap from building basic web pages to building full web applications.
CORS (Cross Origin Resource Sharing)
XHR is a browser-level API that automatically handles myriad low-level details such as caching, handling redirects, content negotiation, authentication, and much more. This serves a dual purpose. First it makes the application APIs much easier to work with, allowing us to focus on the business logic. But, second, it allows the browser to sandbox and enforce a set of security and policy constraints on the application code.
The XHR interfaces enforces strict HTTP semantics on each request. While the XHR API allows the application to add custom HTTP headers (via the SetRequestHeader() method) there are a number of protected headers that are off-limits to application code:
- Accept-Charset, Accept-Encoding, Access-Control-*
- Host, Upgrade, Connection, Referrer, Origin
- Cookie, Sec-, Proxy-, and lots more
The browser will refuse to override any of the unsafe headers. Protecting the Origin header is the key piece of the ‘same-origin policy’ applied to all XHR requests.
- An origin is defined as a triple of application protocol, domain name, and port number (example: https, google.com, 443)
The motivation for CORS is simple, the browser stores vulnerable information, such as auth tokens, cookies, and other private metadata, which cannot be leaked across applications.
The browser automatically appends the protected Origin HTTP header, which advertises the origin from where the request is being made. In turn, the remote server is then able to examine the Origin header and decide if it should allow the request by returning an Access-Control-Allow-Origin header in its response.
- CORS requests omit user credentials such as cookies and auth tokens
Polling with XHR
XHR enables a simple and efficient way to sync client updates with the server. Whenever necessary, an XHR request is dispatched by the client to update the appropriate data on the server. However, the same problem, in reverse, is much more difficult. If data is updated on the server, how does the server notify the client? The answer is that the client must poll the server.