# OneDrive Integration with React: Step-by-Step Guide

In this post, I’ll share how to integrate [Microsoft OneDrive](https://onedrive.live.com/login/) with your [React application](https://www.webdevstory.com/building-blogging-site-react-php/).

We’ll explore the steps for OAuth 2.0 authentication, getting access and refresh tokens, managing file uploads, and addressing challenges like ETag conflicts and CORS issues.

## **Prerequisites**

Before we dive into the technical details, ensure you have:

1. A Microsoft account with OneDrive
    
2. An application registered in Azure Portal for OneDrive API access
    
3. Node.js installed on your system
    
4. Install axios to make API calls to [Microsoft’s Graph API](https://developer.microsoft.com/en-us/graph/graph-explorer)
    

```javascript
npm install axios
```

## **Step 1: Register a OneDrive App in Azure**

To begin, you need to register an app in Azure to get the client ID and client secret for OAuth 2.0.

1. Go to the Azure Portal: [Azure Portal](https://portal.azure.com/)
    
2. **App Registration:**
    

* Navigate to **Microsoft Entra ID &gt; App Registrations &gt; New Registration**.
    
* Set a name for the app and configure the supported account types.
    
* Set your Redirect URI (e.g., `http://localhost:3000` for local development).
    

3\. API Permissions:

* Add Microsoft Graph Permissions for **Files.ReadWrite.All** and **offline\_access** to enable full access to the OneDrive files.
    

**4\. Create a Client Secret:**

* Go to **Certificates & Secrets**, generate a client secret, and store it securely. You’ll need this to generate access tokens.
    

## **Step 2: OAuth 2.0 Authentication Flow**

Once you register your app in Azure, you can generate access and refresh tokens using the OAuth 2.0 flow.

1. Use the Authorization URL to generate the first access and refresh tokens
    

```javascript
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
client_id=YOUR_CLIENT_ID&
response_type=code&
redirect_uri=YOUR_REDIRECT_URI&
scope=openid profile Files.ReadWrite.All offline_access
```

Replace `YOUR_CLIENT_ID` and `YOUR_REDIRECT_URI` with your values. Once the user signs in, the system will provide an **authorization code**.

2\. Exchange Authorization Code for Tokens: Use the following POST request to exchange the authorization code for access and refresh tokens

```javascript
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
```

**Request Body:**

```javascript
client_id=YOUR_CLIENT_ID
client_secret=YOUR_CLIENT_SECRET
code=AUTHORIZATION_CODE
redirect_uri=YOUR_REDIRECT_URI
grant_type=authorization_code
scope=Files.ReadWrite.All offline_access
```

## **Step 3: Refresh Token Flow**

Since OneDrive access tokens expire after **1 hour**, you must refresh tokens to maintain long-term access. Here’s how you refresh the token:

1. **Use the refresh token to get a new access token**
    

```javascript
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
```

**Request Body:**

```javascript
client_id=YOUR_CLIENT_ID
client_secret=YOUR_CLIENT_SECRET
refresh_token=YOUR_REFRESH_TOKEN
redirect_uri=YOUR_REDIRECT_URI
grant_type=refresh_token
scope=Files.ReadWrite.All offline_access
```

[![Meta Advanced React course details on Coursera](https://miro.medium.com/v2/resize:fit:700/1*Wq8uf2ohVEPAmE_0XcuY8Q.png align="left")](https://imp.i384100.net/21bMDA)

## **Step 4: OneDrive File Upload via Graph API**

With OneDrive authentication set up, we can now upload files to OneDrive. Below is an example of how to upload files via the Graph API:

1. **PUT request for file upload**
    

**Request Body**

Send the file data as binary content in the body and pass the access token in the header.

```javascript
const uploadFileToOneDrive = async (path, fileContent) => {
    const response = await axios.put(
        `https://graph.microsoft.com/v1.0/me/drive/root:${path}:/content`,
        fileContent, {
            headers: {
                Authorization: `Bearer ${process.env.REACT_APP_ONEDRIVE_ACCESS_TOKEN}`,
                'Content-Type': 'application/octet-stream',
            },
        }
    );
    return response.data;
};
```

## **Step 5: Handling File Conflicts with ETags**

OneDrive uses **ETags** to manage file versions, and you may encounter conflicts during file updates of the same file. To replace files, you need to handle ETag conflicts properly.

1. **Conflict Behavior**
    

To replace a file, use the following request with conflict behavior handling:

```javascript
PUT https://graph.microsoft.com/v1.0/me/drive/root:/YOUR_PATH:/content?conflictBehavior=replace
```

[![Hacking APIs book cover by Corey Ball, breaking web application programming interfaces](https://miro.medium.com/v2/resize:fit:700/1*IscfPWu-jWr4ZJTl1bVd9Q.jpeg align="left")](https://amzn.to/47Erbb3)

## **Step 6: Downloading Assets from OneDrive**

1. **Fetch File Metadata**
    

Before downloading a file, fetch its metadata for details like the filename, size, or URL.

* GET Request for File Metadata:
    

```javascript
GET https://graph.microsoft.com/v1.0/me/drive/root:/YOUR_PATH:/content
```

* This request will return metadata for the file at YOUR\_PATH.
    

Example Response:

```javascript
 {
     "id": "file_id",
     "name": "example.txt",
     "size": 1024,
     "createdDateTime": "2023-09-21T12:00:00Z",
     "webUrl": "https://onedrive.live.com/..."
 }
```

**2\. Download File Content**

You’ll use the GET method, along with the file path, to download the actual file content and retrieve the file’s download URL or content.

1. **GET Request for File Download**
    

```javascript
GET https://graph.microsoft.com/v1.0/me/drive/root:/YOUR_PATH:/content
```

You can download the file by making an API call to the Graph API endpoint:

```javascript
const downloadAssetFromOneDrive = async (path) => {
    try {
        const response = await axios.get(
            `https://graph.microsoft.com/v1.0/me/drive/root:${path}:/content`, {
                headers: {
                    Authorization: `Bearer ${process.env.REACT_APP_ONEDRIVE_ACCESS_TOKEN}`,
                },
                responseType: 'blob', // Ensures the response is treated as binary data (for files)
            }
        );

        // Create a URL for the blob to allow download
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;

        // Extract the filename from the path
        const fileName = path.split('/').pop();
        link.setAttribute('download', fileName); // Set the download attribute with the file name

        // Append link to the document and simulate click for download
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        console.log("File downloaded successfully");
    } catch (error) {
        console.error("Error downloading the file from OneDrive", error);
    }
};
```

🚀 Before You Go:

👏 Found this OneDrive + React guide helpful? Give it a like!  
💬 Used OneDrive API before? Share your insights!  
🔄 Know someone who needs this? Share the post!

🌟 Your support keeps us going!

Note: Some links on this page might be affiliate links. If you make a purchase through these links, I may earn a small commission at no extra cost to you. Thanks for your support!
