Socket
Socket
Sign inDemoInstall

@segment/analytics-node

Package Overview
Dependencies
4
Maintainers
229
Versions
41
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.0.1-beta.3 to 0.0.1-beta.4

2

dist/cjs/package.json
{
"name": "@segment/analytics-node",
"version": "0.0.1-beta.3",
"version": "0.0.1-beta.4",
"main": "./dist/cjs/src/index.js",

@@ -5,0 +5,0 @@ "module": "./dist/esm/src/index.js",

{
"name": "@segment/analytics-node",
"version": "0.0.1-beta.3",
"version": "0.0.1-beta.4",
"main": "./dist/cjs/src/index.js",

@@ -5,0 +5,0 @@ "module": "./dist/esm/src/index.js",

{
"name": "@segment/analytics-node",
"version": "0.0.1-beta.3",
"version": "0.0.1-beta.4",
"main": "./dist/cjs/src/index.js",

@@ -5,0 +5,0 @@ "module": "./dist/esm/src/index.js",

@@ -1,7 +0,7 @@

## Warning: Until 1.x release, use this library at your own risk!
# @segment/analytics-node
> ### Warning: Until 1.x release, use this library at your own risk!
While the API is very similar, the documentation for the legacy SDK (`analytics-node`) is here: https://segment.com/docs/connections/sources/catalog/libraries/server/node/
## Requirements
- NodeJS >= 14.x
- Node.js >= 14

@@ -25,3 +25,2 @@ ## Quick Start

app.post('/login', (req, res) => {

@@ -32,2 +31,3 @@ analytics.identify({

})
res.sendStatus(200)
})

@@ -41,14 +41,30 @@

})
res.sendStatus(200)
});
```
## Regional configuration
For Business plans with access to Regional Segment, you can use the host configuration parameter to send data to the desired region:
Oregon (Default) — api.segment.io/v1
Dublin — events.eu1.segmentapis.com
An example of setting the host to the EU endpoint using the Node library would be:
```ts
const analytics = new Analytics('YOUR_WRITE_KEY', {
host: "https://events.eu1.segmentapis.com"
});
```
## Complete Settings / Configuration
See complete list of settings in the [AnalyticsSettings interface](src/app/settings.ts).
```ts
new Analytics({
const analytics = new Analytics({
writeKey: '<MY_WRITE_KEY>',
plugins: [plugin1, plugin2],
host: 'https://api.segment.io',
path: '/v1/batch',
maxRetries: 3,
maxEventsInBatch: 15,
flushInterval: 10000,
plugins: [plugin1, plugin2],
// ... and more!

@@ -59,3 +75,39 @@ })

## Graceful Shutdown
## Batching
Our libraries are built to support high performance environments. That means it is safe to use our Node library on a web server that’s serving thousands of requests per second.
Every method you call does not result in an HTTP request, but is queued in memory instead. Messages are then flushed in batch in the background, which allows for much faster operation.
By default, our library will flush:
- The very first time it gets a message.
- Every 15 messages (controlled by `settings.maxEventsInBatch`).
- If 10 seconds has passed since the last flush (controlled by `settings.flushInterval`)
There is a maximum of 500KB per batch request and 32KB per call.
If you don’t want to batch messages, you can turn batching off by setting the `maxEventsInBatch` setting to 1, like so:
```ts
const analytics = new Analytics({ '<MY_WRITE_KEY>', { maxEventsInBatch: 1 });
```
Batching means that your message might not get sent right away. But every method call takes an optional callback, which you can use to know when a particular message is flushed from the queue, like so:
```ts
analytics.track({
userId: '019mr8mf4r',
event: 'Ultimate Played'
callback: (ctx) => console.log(ctx)
})
```
## Error Handling
Subscribe and log all event delivery errors.
```ts
const analytics = new Analytics({ writeKey: '<MY_WRITE_KEY>' })
analytics.on('error', (err) => console.error(err))
```
## Graceful Shutdown (Long or short running processes)
### Avoid losing events on exit!

@@ -77,2 +129,3 @@ * Call `.closeAndFlush()` to stop collecting new events and flush all existing events.

const app = express()
app.post('/cart', (req, res) => {

@@ -84,15 +137,17 @@ analytics.track({

})
});
res.sendStatus(200)
})
const server = app.listen(3000)
const onExit = async () => {
console.log("Gracefully closing server...");
await analytics.closeAndFlush() // flush all existing events
server.close(() => process.exit());
};
server.close(() => {
console.log("Gracefully closing server...")
process.exit()
})
}
process.on("SIGINT", onExit);
process.on("SIGTERM", onExit);
['SIGINT', 'SIGTERM'].forEach((code) => process.on(code, onExit))
```

@@ -113,12 +168,120 @@

## Event Emitter
## Event Emitter Interface
```ts
// listen globally to events
analytics.on('identify', (ctx) => console.log(ctx.event))
// subscribe to identify calls
analytics.on('identify', (err) => console.error(err))
// listen for errors (if needed)
analytics.on('error', (err) => console.error(err))
// subscribe to a specific event
analytics.on('track', (ctx) => console.log(ctx))
```
## Multiple Clients
Different parts of your application may require different types of batching, or even sending to multiple Segment sources. In that case, you can initialize multiple instances of Analytics with different settings:
```ts
import { Analytics } from '@segment/analytics-node'
const marketingAnalytics = new Analytics('MARKETING_WRITE_KEY');
const appAnalytics = new Analytics('APP_WRITE_KEY');
```
## Troubleshooting
1. Double check that you’ve followed all the steps in the Quick Start.
2. Make sure that you’re calling a Segment API method once the library is successfully installed: identify, track, etc.
3. Log events and errors the event emitter:
```js
['initialize', 'call_after_close',
'screen', 'identify', 'group',
'track', 'ready', 'alias',
'page', 'error', 'register',
'deregister'].forEach((event) => analytics.on(event, console.log)
```
## Differences from legacy analytics-node / Migration Guide
- Named imports.
```ts
// old
import Analytics from 'analytics-node'
// new
import { Analytics } from '@segment/analytics-next'
```
- Instantiation requires an object
```ts
// old
var analytics = new Analytics('YOUR_WRITE_KEY');
// new
const analytics = new Analytics({ writeKey: 'YOUR_WRITE_KEY' });
```
- Graceful shutdown (See Graceful Shutdown section)
```ts
// old
await analytics.flush(function(err, batch) {
console.log('Flushed, and now this program can exit!');
});
// new
await analytics.closeAndFlush()
```
Other Differences:
- The `enable` configuration option has been removed-- see "Disabling Analytics" section
- the `errorHandler` configuration option has been remove -- see "Error Handling" section
- `flushAt` configuration option -> `maxEventsInBatch`.
- `callback` option is moved to configuration
```ts
// old
analytics.track({
userId: '019mr8mf4r',
event: 'Ultimate Played'
}), function(err, batch){
if (err) {
console.error(err)
}
});
// new
analytics.track({
userId: '019mr8mf4r',
event: 'Ultimate Played',
callback: (ctx) => {
if (ctx.failedDelivery()) {
console.error(ctx)
}
}
})
```
## Development / Disabling Analytics
- If you want to disable analytics for unit tests, you can use something like [nock](https://github.com/nock/nock) or [jest mocks](https://jestjs.io/docs/manual-mocks).
You should prefer mocking. However, if you need to intercept the request, you can do:
```ts
// Note: nock will _not_ work if polyfill fetch with something like undici, as nock uses the http module. Undici has its own interception method.
import nock from 'nock'
const mockApiHost = 'https://foo.bar'
const mockPath = '/foo'
nock(mockApiHost) // using regex matching in nock changes the perf profile quite a bit
.post(mockPath, (body) => true)
.reply(201)
.persist()
const analytics = new Analytics({ host: mockApiHost, path: mockPath })
```
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc