Last active
March 17, 2021 01:23
-
-
Save emeraldsanto/fef48904768084dc18da8c65c25e73fa to your computer and use it in GitHub Desktop.
Segment proxy (Node)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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