onedrive-business

n8n custom node for OneDrive Business with robust deduplication and webhook triggers

Package Information

Downloads: 3 weekly / 107 monthly
Latest Version: 1.3.0
Author: CS1ANHNT

Documentation

OneDrive Business Custom Node for n8n

Production-ready OneDrive Business integration for n8n with robust deduplication and webhook-based triggers.

Features

✅ OneDrive Business ONLY

  • Tenant-based authentication via Azure Entra ID (OAuth2)
  • Supports User Drives (/users/{userId}/drive)
  • Supports SharePoint Site Drives (/sites/{siteId}/drive)
  • NOT for OneDrive Personal/Consumer

📁 File Operations

  • Upload: Binary file upload with automatic MIME type detection
  • Download: Binary file download
  • Get: Retrieve file metadata
  • Delete: Remove files
  • Rename: Rename files
  • Search: Search for files
  • Share: Create sharing links (view/edit, anonymous/organization)

📂 Folder Operations

  • Create: Create folders
  • Delete: Remove folders
  • Get Items: List folder contents
  • Rename: Rename folders
  • Search: Search for folders
  • Share: Create sharing links

🔔 Trigger Node (Webhook + Delta Query)

  • File Created: Trigger when new files are uploaded
  • File Updated: Trigger when files are modified
  • Folder Created: Trigger when new folders are created
  • Folder Updated: Trigger when folders are modified

Installation

cd ~/.n8n/custom
git clone <your-repo> n8n-nodes-onedrive-business
cd n8n-nodes-onedrive-business
npm install
npm run build

Restart n8n to load the custom node.

Azure App Registration Setup

1. Create App Registration

  1. Go to Azure Portal
  2. Navigate to Azure Active DirectoryApp registrations
  3. Click New registration
  4. Enter name: n8n OneDrive Business
  5. Select Accounts in this organizational directory only (or multi-tenant if needed)
  6. Set Redirect URI: https://your-n8n-instance.com/rest/oauth2-credential/callback
  7. Click Register

2. Configure API Permissions

  1. Go to API permissions
  2. Click Add a permissionMicrosoft GraphDelegated permissions
  3. Add these permissions:
    • Files.ReadWrite.All
    • Sites.ReadWrite.All
    • offline_access
  4. Click Add permissions
  5. Click Grant admin consent (requires admin)

3. Create Client Secret

  1. Go to Certificates & secrets
  2. Click New client secret
  3. Enter description: n8n integration
  4. Select expiration (recommend 24 months)
  5. Click Add
  6. Copy the secret value immediately (you won't see it again)

4. Get Required IDs

  • Application (client) ID: Copy from Overview page
  • Directory (tenant) ID: Copy from Overview page

Configuration in n8n

1. Create Credential

  1. In n8n, go to CredentialsNew
  2. Search for OneDrive Business OAuth2 API
  3. Fill in:
    • Tenant ID: Your Azure AD tenant ID (or "common" for multi-tenant)
    • Client ID: Application ID from Azure
    • Client Secret: Secret value from Azure
  4. Click Connect my account
  5. Sign in with a Microsoft 365 account
  6. Grant permissions

2. Use in Workflows

File Upload Example

1. Add "OneDrive Business" node
2. Select Resource: File
3. Select Operation: Upload
4. Drive Type: User Drive
5. User ID: user@contoso.com
6. File Path: /Documents/report.pdf
7. Binary Property: data

Trigger Example

1. Add "OneDrive Business Trigger" node
2. Drive Type: User Drive
3. User ID: user@contoso.com
4. Trigger On: File Created, File Updated
5. Activate workflow

Deduplication Architecture

The Problem

SharePoint-backed OneDrive generates multiple updates per file upload:

  1. File created (size=0, no hash)
  2. Metadata updated
  3. Content uploaded (partial hash)
  4. Final metadata sync (complete hash)

Without deduplication, ONE upload = FOUR workflow executions.

The Solution

This node implements a 4-layer deduplication strategy:

1. File Stability Checking

function isStable(item): boolean {
  return (
    item.size > 0 &&
    item.file?.hashes?.quickXorHash &&
    item.lastModifiedDateTime === item.fileSystemInfo?.lastModifiedDateTime
  );
}

Ensures files have completed uploading before processing.

2. Version-based Tracking

const versionKey = `${item.id}_${item.eTag}`;

Each file version (identified by eTag) is processed exactly once.

3. Stability Window

if (Date.now() - lastModified < 15000) {
  deferProcessing(); // Wait 15 seconds
}

Prevents processing files still being modified.

4. Event Classification

if (!previousState[item.id]) {
  event = 'file.created';
} else if (item.eTag !== previousState[item.id].eTag) {
  event = 'file.updated';
}

Accurately distinguishes between created and updated events.

State Persistence

State is stored in:

~/.n8n-state/onedrive-business/{nodeId}.json

Contains:

  • deltaLink: Microsoft Graph delta query continuation token
  • processedVersions: Map of ${itemId}_${eTag}true
  • lastKnownItems: Map of itemId{ eTag, lastModifiedDateTime }

Survives n8n restarts to prevent duplicate re-processing.

Webhook Architecture

Why Webhook + Delta Query?

Microsoft Graph webhooks do NOT contain file data. They only notify that "something changed."

The Delta Query is the single source of truth.

Flow

1. File uploaded to OneDrive
   ↓
2. Microsoft Graph sends webhook notification
   ↓
3. Webhook endpoint returns 200 OK (does NOT trigger workflow)
   ↓
4. n8n polls trigger node (every 60 seconds)
   ↓
5. Trigger fetches Delta Query
   ↓
6. DeltaProcessor applies deduplication
   ↓
7. Workflow triggered with deduplicated events

Why This Works

  • Webhook: Low-latency notification (near real-time)
  • Delta Query: Complete file metadata + pagination
  • Deduplication: Collapses multiple updates into one event
  • State Persistence: Prevents re-processing after restarts

API Rate Limits

Microsoft Graph has rate limits:

  • Per app per tenant: 10,000 requests per 10 minutes
  • Per user: 2,000 requests per second

This node implements:

  • Exponential backoff for 429 responses
  • Retry-After header parsing
  • Automatic retry (up to 3 attempts)

Troubleshooting

No Webhook Notifications Received

  1. Verify n8n is publicly accessible (webhook URL must be reachable)
  2. Check firewall rules
  3. Verify SSL certificate (Microsoft Graph requires HTTPS)
  4. Check n8n logs for webhook validation errors

Duplicate Workflow Executions

  1. Check if deduplication is working:
    • View ~/.n8n-state/onedrive-business/{nodeId}.json
    • Verify processedVersions is being populated
  2. Increase stability window if large files are being processed
  3. Check that eTag is changing between updates

Subscription Expired

Subscriptions auto-renew every 2 days. If renewal fails:

  1. Check OAuth2 token validity
  2. Verify API permissions are still granted
  3. Manually deactivate and reactivate the trigger node

Delta Query Not Working

  1. Verify drive path is correct:
    • User drive: /users/{userId}/drive
    • Site drive: /sites/{siteId}/drive
  2. Check that user/site ID is valid
  3. Ensure credentials have Files.ReadWrite.All permission

Development

Build

npm run build

Watch Mode

npm run dev

Lint

npm run lint
npm run lintfix

License

MIT

Support

For issues, feature requests, or contributions, please open an issue on GitHub.


✔ How this OneDrive Business node avoids duplicate executions

Problem Statement

OneDrive Business is backed by SharePoint, which generates multiple Graph API notifications for a single file upload:

  1. File Created: Empty placeholder (size=0)
  2. Metadata Updated: File properties set
  3. Content Uploaded: Binary data written (partial hash)
  4. Final Sync: Hash finalized, timestamps aligned

Each of these generates a separate webhook notification and appears in the Delta Query.

Without deduplication: Uploading one 10MB PDF would trigger 4 workflow executions.

Solution Architecture

1. Webhook as Notification Only

The webhook endpoint never emits workflow data. It only:

  • Validates the request (clientState check)
  • Returns 200 OK
  • Functions as a "wake-up call" for the polling mechanism

Result: Webhook notifications don't directly trigger workflows, eliminating one source of duplicates.

2. Delta Query as Single Source of Truth

All workflow triggers come from the Delta Query (GET /drive/root/delta), which:

  • Provides complete file metadata
  • Handles pagination
  • Returns a @odata.deltaLink for continuing from the last check

Result: Only one API provides workflow data, creating a single choke point for deduplication.

3. eTag-based Version Tracking

Each file version has a unique eTag value. The node tracks:

processedVersions: {
  "fileId123_etag-v1": true,
  "fileId123_etag-v2": true,
  "fileId123_etag-v3": true
}

Before emitting a workflow event:

const versionKey = `${item.id}_${item.eTag}`;
if (processedVersions[versionKey]) {
  return; // Already processed
}
processedVersions[versionKey] = true;
// Emit workflow event

Result: Each file version triggers exactly one workflow execution, regardless of how many times it appears in Delta Query.

4. File Stability Window

Some uploads take time to finalize (especially large files). The node waits for:

  • size > 0
  • quickXorHash present
  • lastModifiedDateTime matches fileSystemInfo.lastModifiedDateTime
  • ✅ 15 seconds elapsed since last modification

If these conditions aren't met, the file is deferred (not processed yet).

Result: Only stable, fully uploaded files trigger workflows.

5. State Persistence Across Restarts

All deduplication state is saved to disk:

~/.n8n-state/onedrive-business/{nodeId}.json

When n8n restarts:

  1. State is loaded from disk
  2. deltaLink is restored
  3. processedVersions map is restored
  4. Delta Query continues from where it left off

Result: Restarting n8n doesn't cause already-processed files to re-trigger workflows.

Real-World Example

Scenario: User uploads report.pdf (10MB) to OneDrive Business.

What happens in SharePoint:

0s:  File created (size=0, no hash)              → eTag-v1
1s:  Metadata set (name, path)                   → eTag-v2
2s:  Content upload starts (partial hash)        → eTag-v3
5s:  Content upload completes (quickXorHash set) → eTag-v4
6s:  Final metadata sync                         → eTag-v5

Without this node (naive approach):

  • Delta Query returns 5 versions
  • 5 workflow executions 😱

With this node:

Delta Query returns 5 versions:

Version 1 (eTag-v1):
  ❌ size=0 → Not stable, deferred

Version 2 (eTag-v2):
  ❌ size=0 → Not stable, deferred

Version 3 (eTag-v3):
  ❌ No quickXorHash → Not stable, deferred

Version 4 (eTag-v4):
  ✅ size=10485760
  ✅ quickXorHash present
  ✅ Timestamps aligned
  ❌ Modified 2 seconds ago → Within stability window, deferred

Version 5 (eTag-v5):
  ✅ size=10485760
  ✅ quickXorHash present
  ✅ Timestamps aligned
  ✅ Modified 20 seconds ago → Stable!
  ✅ Not in processedVersions
  
  → Mark as processed: processedVersions["fileId123_etag-v5"] = true
  → Emit workflow event: { event: 'file.created', item: {...} }

Result: 1 workflow execution

Why This Matters for Production

In a real Microsoft 365 tenant with hundreds of users:

  • 100 files uploaded per day
  • Without deduplication: 400+ workflow executions
  • With this node: 100 workflow executions

75% reduction in duplicate workflows, preventing:

  • Wasted compute resources
  • Duplicate notifications to users
  • Redundant database writes
  • API quota exhaustion

This architecture ensures enterprise-grade reliability for OneDrive Business integrations.

Discussion