Hey there, fellow JavaScript dev! Ready to supercharge your OneDrive integration with webhooks? You're in the right place. This guide will walk you through setting up webhooks for OneDrive using the Microsoft Graph API. We'll keep things concise and code-heavy, just the way we like it.
Webhooks are the secret sauce for real-time updates in your OneDrive integration. They let your app know instantly when changes happen, saving you from constant polling. Pretty neat, right?
Before we dive in, make sure you've got:
axios
and express
packages ready to goGot all that? Great! Let's get our hands dirty.
First things first, we need to create a subscription. Here's how you do it:
const axios = require('axios'); async function createSubscription(accessToken) { const response = await axios.post( 'https://graph.microsoft.com/v1.0/subscriptions', { changeType: 'created,updated', notificationUrl: 'https://your-app.com/webhook', resource: '/me/drive/root', expirationDateTime: new Date(Date.now() + 3600 * 1000).toISOString(), clientState: 'secretClientState' }, { headers: { Authorization: `Bearer ${accessToken}` } } ); return response.data; }
This snippet creates a subscription for file creation and updates in the root folder. Adjust the resource
and changeType
as needed.
Microsoft needs to make sure it's really you. Set up an endpoint to handle the validation:
const express = require('express'); const app = express(); app.post('/webhook', (req, res) => { if (req.query && req.query.validationToken) { res.set('Content-Type', 'text/plain'); res.send(req.query.validationToken); } else { // Handle actual notifications here res.sendStatus(202); } }); app.listen(3000, () => console.log('Webhook server running on port 3000'));
When changes happen, you'll get a notification. Here's how to handle it:
app.post('/webhook', (req, res) => { if (req.query && req.query.validationToken) { // Validation handling (as shown above) } else { const notifications = req.body.value; notifications.forEach(notification => { console.log(`Change type: ${notification.changeType}`); console.log(`Resource: ${notification.resource}`); // Process the notification }); res.sendStatus(202); } });
Subscriptions expire, so you'll need to renew them. Here's a quick way to do it:
async function renewSubscription(accessToken, subscriptionId) { const response = await axios.patch( `https://graph.microsoft.com/v1.0/subscriptions/${subscriptionId}`, { expirationDateTime: new Date(Date.now() + 3600 * 1000).toISOString() }, { headers: { Authorization: `Bearer ${accessToken}` } } ); return response.data; }
Pro tip: Set up a job to renew subscriptions before they expire. Your future self will thank you!
clientState
in notifications to ensure they're legit.Here's a quick error handling snippet:
try { await createSubscription(accessToken); } catch (error) { if (error.response && error.response.status === 429) { // Handle rate limiting console.log('Rate limited. Retrying after', error.response.headers['retry-after']); } else { console.error('Error creating subscription:', error.message); } }
And there you have it! You're now equipped to implement webhooks in your OneDrive integration. Remember, this is just the beginning. Play around with different change types, resources, and see what cool features you can build.
Want to dive deeper? Check out these resources:
Happy coding, and may your webhooks always be responsive!