Hey there, fellow JavaScript dev! Ready to supercharge your app with real-time updates from Microsoft Graph? Let's dive into the world of webhooks and get your user-facing integration up and running in no time.
Webhooks in Microsoft Graph API are like your app's personal news feed. They notify you when something interesting happens, like a new email or calendar event. For user-facing integrations, this means you can keep your app in sync with Microsoft 365 data without constantly polling the API. Pretty neat, right?
Make sure you've got these in your toolkit:
Got all that? Great! Let's get our hands dirty.
First things first, we need to create a subscription. This is like telling Microsoft, "Hey, let me know when something changes!"
Here's how you do it:
const axios = require('axios'); async function createSubscription() { const subscription = { changeType: 'created,updated', notificationUrl: 'https://your-app.com/webhook', resource: '/me/messages', expirationDateTime: new Date(Date.now() + 3600 * 1000).toISOString(), clientState: 'secretClientState' }; try { const response = await axios.post('https://graph.microsoft.com/v1.0/subscriptions', subscription, { headers: { Authorization: `Bearer ${accessToken}` } }); console.log('Subscription created:', response.data); } catch (error) { console.error('Error creating subscription:', error.response.data); } }
Now, Microsoft needs to make sure your endpoint is legit. They'll send a validation token to your notificationUrl
. Here's how to handle it:
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); } });
Now that you're all set up, let's handle those juicy notifications:
app.post('/webhook', (req, res) => { if (req.query && req.query.validationToken) { // Validation handling (as shown above) } else { const notifications = req.body.value; notifications.forEach(async (notification) => { if (notification.clientState === 'secretClientState') { // Process the notification await processNotification(notification); } }); res.sendStatus(202); } }); async function processNotification(notification) { // Fetch the changed resource const response = await axios.get(`https://graph.microsoft.com/v1.0${notification.resource}`, { headers: { Authorization: `Bearer ${accessToken}` } }); // Update your app's state updateAppState(response.data); }
Subscriptions don't last forever. You'll need to renew them before they expire:
async function renewSubscription(subscriptionId) { const expirationDateTime = new Date(Date.now() + 3600 * 1000).toISOString(); try { const response = await axios.patch(`https://graph.microsoft.com/v1.0/subscriptions/${subscriptionId}`, { expirationDateTime }, { headers: { Authorization: `Bearer ${accessToken}` } }); console.log('Subscription renewed:', response.data); } catch (error) { console.error('Error renewing subscription:', error.response.data); } }
And when you're done, don't forget to clean up:
async function deleteSubscription(subscriptionId) { try { await axios.delete(`https://graph.microsoft.com/v1.0/subscriptions/${subscriptionId}`, { headers: { Authorization: `Bearer ${accessToken}` } }); console.log('Subscription deleted'); } catch (error) { console.error('Error deleting subscription:', error.response.data); } }
Remember these golden rules:
clientState
in notifications.And there you have it! You're now ready to give your users real-time updates from Microsoft Graph. Remember, webhooks are powerful, but with great power comes great responsibility. Use them wisely, and your app will be the talk of the town!
Want to dive deeper? Check out the official Microsoft Graph documentation for more advanced topics like batching operations and subscription migration.
Now go forth and webhook like a pro! 🚀