@rudderstack/rudder-sdk-node
v3.1.1
Published
Rudder Node SDK
Keywords
Readme
RudderStack Node.js SDK
The RudderStack Node.js SDK lets you track your customer event data from your Node.js applications and send it to your specified destinations.
Refer to the documentation for more details.
Installing the SDK
Run the following command to install the Node.js SDK via npm:
$ npm install @rudderstack/rudder-sdk-nodeUsing the SDK
To create a global RudderStack client object and use it for the subsequent event calls, run the following snippet:
const Analytics = require('@rudderstack/rudder-sdk-node');
const client = new Analytics(WRITE_KEY, {
dataPlaneUrl: DATA_PLANE_URL, // default: https://hosted.rudderlabs.com
});Using the SDK with Deno
Core in-memory event delivery has been verified with Deno 2.9.6 and the published SDK version 3.0.12. See the Deno example for a runnable npm import, required permissions, and current limitations.
The example requires network access and unrestricted --allow-env permission.
Bull/Redis persistence is not fully supported on Deno and is not recommended.
Deno can resend timed-out requests, and queue recovery and shutdown have known limitations.
SDK Initialization Options
Below parameters are optional and can be passed during SDK initialization.
| Name | Type | Default value | Description |
| :--------------------- | :------- | :------------------------------ | :------------------------------------------------------------------------------------------------ |
| dataPlaneUrl | String | https://hosted.rudderlabs.com | The data plane URL. |
| path | String | /v1/batch | Path to batch endpoint. |
| flushAt | Number | 20 | The number of events to be flushed when reached this limit. |
| flushInterval | Number | 10000 | The maximum timespan (in milliseconds) after which the events from the in-memory queue is flushed |
| maxQueueSize | Number | 460800(500kb) | Maximum size in bytes (UTF-8, including the batch envelope) of a batch request body |
| maxInternalQueueSize | Number | 20000 | The maximum length of the in-memory queue |
| logLevel | String | 'info' | Log level. Ex: 'debug', 'error' |
| axiosConfig | Object | N/A | Axios config |
| axiosInstance | Object | N/A | Axios instance |
| axiosRetryConfig | Object | N/A | Axios retry configuration |
| retryCount | Number | 3 | Number of times requests will be retried by axios if failed |
| errorHandler | Function | N/A | Called when a server request or persistent-queue add fails; without it, the latter is only logged |
| gzip | Boolean | true | Whether to compress request with gzip or not |
| beforeEnqueue | Function | N/A | Edits or drops each event before it is queued. See Before-enqueue hook |
| beforeEnqueueOnError | String | 'send' | 'send' the original event or 'drop' it when beforeEnqueue fails |
Before-enqueue hook
beforeEnqueue runs synchronously once per event, after the SDK adds messageId, originalTimestamp, context and channel, and before the event is queued. It gets its own copy of the event. Return the event, edited or not, to send it, or null to drop it. A dropped event still calls the callback, without an error. The hook must be synchronous, and it does not run again for retries or persistent-queue replays.
const client = new Analytics(WRITE_KEY, {
dataPlaneUrl: DATA_PLANE_URL,
beforeEnqueue: (event) => {
// Drop events from internal test accounts
if (typeof event.userId === 'string' && event.userId.startsWith('test-')) return null;
// Strip the email before it leaves the process
for (const traits of [event.traits, event.context?.traits]) {
if (traits && typeof traits === 'object') delete traits.email;
}
return event;
},
// The hook redacts PII, so never fall back to the unredacted original
beforeEnqueueOnError: 'drop',
});If the hook throws, returns anything other than an event or null, or returns an event that fails the call's validation (for example, no userId or anonymousId), the SDK logs the error and sends the original event, or drops it with beforeEnqueueOnError: 'drop'. An event of 32KB or larger is sent with the usual size warning, as without a hook.
The hook may change messageId; the changed value is kept. If it is missing or empty, the original is restored without a warning. Changes to channel and context.library are reverted with one warning. A non-function beforeEnqueue or a beforeEnqueueOnError other than 'send' or 'drop' throws when the client is created.
Retry hooks in axiosRetryConfig receive credential-redacted error and request snapshots.
The snapshots omit authentication, raw requests, agents, functions, and other live transport objects.
Payload buffers and nested diagnostic data are independent copies. Changes to snapshot fields do not
change the live retry request. Retry decisions, delays, and asynchronous hook results still apply.
Supported calls
Refer to the SDK documentation for more information on the supported calls.
Initializing the SDK for data persistence
This is a beta feature. Contact us on our Community Slack in case you face any issues.
RudderStack has a data persistence feature to persist the events in Redis, leading to better event delivery guarantees. Also, the SDK can retry event delivery multiple times as the queue is maintained in a different process space(Redis).
| To use this feature, you will need to host a Redis server and use it as the intermediary data storage queue. | | :----------------------------------------------------------------------------------------------------------- |
A sample SDK initialization is shown below:
const client = new Analytics(
"write_key",
{
dataPlaneUrl: DATA_PLANE_URL // default: https://hosted.rudderlabs.com with default path set to /v1/batch
flushAt: <number> = 20,
flushInterval: <ms> = 20000
maxInternalQueueSize: <number> = 20000 // the max number of elements that the SDK can hold in memory,
// this is different than the Redis list created when persistence is enabled
}
);
client.createPersistenceQueue({ redisOpts: { host: "localhost" } }, err => {})To initialize the data persistence queue, you need to call the createPersistenceQueue method which takes two parameters as input - queueOpts and a callback. The createPersistenceQueue method will initialize a Redis list by calling Bull's utility methods.
If you do not call
createPersistenceQueueafter initializing the SDK, the SDK will not implement data persistence.
Read the detailed documentation for more information on createPersistenceQueue and the other configurable parameters.
Event flow
For more information on how the event flow occurs with data persistence enabled, refer to the documentation.
Limitations around data persistence
- Refer to this page to understand the limitations
- For more details on the limitations, read: https://redis.io/topics/cluster-tutorial#redis-cluster-data-sharding
- As a workaround, refer to this page: https://gitter.im/OptimalBits/bull/archives/2018/04/17. We pass a prefix with default value as {rudder}.
Contact us
If you come across any issues while configuring or using the RudderStack Node.js SDK, you can contact us or start a conversation in our Slack community.
