Using the OneDrive API in JavaScript apps (CORS support)

The OneDrive API supports HTTP access control (CORS) to allow single page JavaScript applications to use the OneDrive API through the common XMLHttpRequest pattern.

You can read more about CORS (Cross-Origin Resource Sharing) on Wikipedia or the W3C CORS Wiki.

Sample code

The OneDrive Explorer JS sample app demonstrates how to use the OneDrive API from a JavaScript app. This sample shows you how to browse and navigate the contents of a user's OneDrive in JavaScript.

You can try the OneDrive explorer sample app or view the source code.

Example request

This example creates a CORS request that returns the items from a user's OneDrive, by sending a GET request to the /drive/root/children endpoint. The example was generated using

var createCORSRequest = function(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // Most browsers., url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // IE8 & IE9
    xhr = new XDomainRequest();, url);
  } else {
    // CORS not supported.
    xhr = null;
  return xhr;

var url = '';
var method = 'GET';
var xhr = createCORSRequest(method, url);

xhr.onload = function() {
  // Success code goes here.

xhr.onerror = function() {
  // Error code goes here.

xhr.setRequestHeader('Authorization', 'Bearer access_token_value');

Downloading OneDrive files in JavaScript apps

To download files from OneDrive in a JavaScript app you cannot use the /content API, since this responds with a 302 redirect. A 302 redirect is explicitly prohibited when a CORS preflight is required, such as when providing the Authorization header.

Instead, your app needs to select the @microsoft.graph.downloadUrl property, which returns the same URL that /content would have redirected to. This URL can then be requested directly using XMLHttpRequest. Because these URLs are pre-authenticated they can be retrieved without a CORS preflight request.


To retrieve the download URL for a file, first make a request that includes the @microsoft.graph.downloadUrl property:

GET /drive/items/{item-id}?select=id,@microsoft.graph.downloadUrl

This returns the id and download URL for a file:

HTTP/1.1 200 OK
Content-Type: application/json

  "id": "12319191!11919",
  "@microsoft.graph.downloadUrl": "https://..."

You can then make an XMLHttpRequest for the URL provided in @microsoft.graph.downloadUrl to retrieve the file.