Skip to content

Instantly share code, notes, and snippets.

@emeraldsanto
Last active March 17, 2021 01:23
Show Gist options
  • Select an option

  • Save emeraldsanto/fef48904768084dc18da8c65c25e73fa to your computer and use it in GitHub Desktop.

Select an option

Save emeraldsanto/fef48904768084dc18da8c65c25e73fa to your computer and use it in GitHub Desktop.
Segment proxy (Node)
import express from 'express';
import Segment from 'analytics-node';
const instance = new Segment('YOUR_WRITE_KEY');
const port = 3000;
const app = express();
// Enables JSON parsing middleware
app.use(express.json())
// Registers the new endpoint which will handle the Segment events
app.post('/analytics/segment/v1/batch', (req, res) => {
const { batch } = req.body;
const results = batch.map((event) => {
/**
* It is important to remove the `messageId` from the event
* when you need to send the same event to multiple destinations.
*
* Otherwise, Segment will only process the first event with
* a given `messageId`.
*/
delete event.messageId;
/**
* Here you can alter the different payload properties
* (context, traits, properties, etc.) to standardize your events.
*
* You could also implement a custom caching layer to prevent sending
* duplicate events for destinations such as Braze.
*/
event.context = {
...event.context,
yourStandardProperty: "a standard value",
};
event.traits = {
...event.traits,
yourOtherStandardProperty: "another standard value",
};
/**
* You could send the "same" event
* more than once, to different destinations,
* with adapted payloads.
*/
event.integrations = {
...event.integrations,
Braze: false,
};
/**
* You can reject (skip) events
* for any arbitraty reasons.
*/
if (event.type === "identify") {
instance.identify(event);
return "handled";
}
return "skipped";
});
res.status(200).send(results);
});
app.listen(port, () => console.log(`Server listening at http://localhost:${port}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment