Salesforce Webhooks & Events
Overview
Salesforce doesn't use traditional webhooks. Instead, it offers Platform Events, Change Data Capture (CDC), and Outbound Messages for real-time data flow. All use the CometD (Bayeux) streaming protocol via jsforce.
Prerequisites
- jsforce installed with connection configured
- Platform Events or CDC enabled in your org
- Understanding of publish/subscribe patterns
- Express.js for Outbound Message endpoints
Event Mechanism Comparison
| Mechanism | Direction | Use Case | Retention |
|---|
| Platform Events | Bi-directional | Custom event bus | 72 hours |
| Change Data Capture (CDC) | Salesforce → External | Record change notifications | 3 days |
| Outbound Messages | Salesforce → External | Workflow-triggered HTTP POST | Until confirmed |
| Streaming API (PushTopics) | Salesforce → External | SOQL-based subscriptions | No replay |
Instructions
Step 1: Subscribe to Change Data Capture (CDC)
import jsforce from 'jsforce';
const conn = new jsforce.Connection({
loginUrl: process.env.SF_LOGIN_URL,
});
await conn.login(process.env.SF_USERNAME!, process.env.SF_PASSWORD! + process.env.SF_SECURITY_TOKEN!);
const subscription = conn.streaming.topic('/data/AccountChangeEvent').subscribe((message) => {
const header = message.payload.ChangeEventHeader;
console.log('Change Type:', header.changeType);
console.log('Record IDs:', header.recordIds);
console.log('Changed Fields:', header.changedFields);
console.log('User ID:', header.commitUser);
if (header.changeType === 'UPDATE') {
console.log('New values:', message.payload);
}
});
Step 2: Publish and Subscribe to Platform Events
await conn.sobject('Order_Status__e').create({
Order_Id__c: 'ORD-12345',
Status__c: 'Shipped',
Amount__c: 499.99,
});
const eventSub = conn.streaming.topic('/event/Order_Status__e').subscribe((message) => {
console.log('Event received:', {
orderId: message.payload.Order_Id__c,
status: message.payload.Status__c,
amount: message.payload.Amount__c,
replayId: message.event.replayId,
});
});
conn.streaming.topic('/event/Order_Status__e', { replayId: - }).( {
});
Step 3: Handle Outbound Messages (SOAP-based)
import express from 'express';
import { parseString } from 'xml2js';
const app = express();
app.use(express.text({ type: 'text/xml' }));
app.post('/salesforce/outbound-message', (req, res) => {
parseString(req.body, (err, result) => {
if (err) {
console.error('XML parse error:', err);
return res.status(400).send('Invalid XML');
}
const notification = result['soapenv:Envelope']['soapenv:Body'][0]
['notifications'][0]['Notification'][0];
const sobject = notification['sObject'][0];
console.log('Record ID:', sobject['sf:Id'][0]);
console.(, sobject.[]);
res.().();
});
});
Step 4: Robust Event Processing
import { Redis } from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);
async function processEvent(message: any): Promise<void> {
const replayId = message.event.replayId;
const eventKey = `sf:event:${replayId}`;
if (await redis.exists(eventKey)) {
console.log(`Event ${replayId} already processed, skipping`);
return;
}
try {
const changeType = message.payload.ChangeEventHeader?.changeType;
const recordIds = message.payload.ChangeEventHeader?.recordIds || [];
switch (changeType) {
case 'CREATE':
await handleRecordCreated(recordIds, message.payload);
break;
:
(recordIds, message.);
;
:
(recordIds);
;
}
redis.(eventKey, , , * );
redis.(, replayId.());
} (error) {
.(, error);
error;
}
}
Output
- CDC subscription for real-time record change notifications
- Platform Event publishing and subscribing
- Outbound Message endpoint with SOAP acknowledgment
- Idempotent event processing with replay ID tracking
Error Handling
| Issue | Cause | Solution |
|---|
403: CDC not enabled | Object not selected for CDC | Setup > Change Data Capture > select objects |
EVENT_OR_PUSHTTOPIC_NOT_FOUND | Platform Event doesn't exist | Create in Setup > Platform Events |
| Missed events | Client disconnected | Use replayId to resume from last position |
| Duplicate processing | No idempotency check | Track processed replayId values in Redis |
| Outbound Message retry | Ack not sent | Return <Ack>true</Ack> XML response |
Resources
Next Steps
For performance optimization, see salesforce-performance-tuning.