From e1a910fecefba5bf333f956201f30c120a448b08 Mon Sep 17 00:00:00 2001 From: Seth Silesky <5115498+silesky@users.noreply.github.com> Date: Thu, 2 Jan 2025 11:23:25 -0600 Subject: [PATCH 1/2] update node README --- packages/node/README.md | 65 +++++++++++++++++++++-------------------- 1 file changed, 34 insertions(+), 31 deletions(-) diff --git a/packages/node/README.md b/packages/node/README.md index 170014285..7153a103c 100644 --- a/packages/node/README.md +++ b/packages/node/README.md @@ -75,22 +75,20 @@ Here is an example of using analytics.js within a handler: ```ts const { Analytics } = require('@segment/analytics-node'); -// since analytics has the potential to be stateful if there are any plugins added, -// to be on the safe side, we should instantiate a new instance of analytics on every request (the cost of instantiation is low). -const analytics = () => new Analytics({ - flushAt: 1, + // Preferable to create a new analytics instance per-invocation. Otherwise, we may get a warning about overlapping flush calls. Also, custom plugins have the potential to be stateful, so we prevent those kind of race conditions. +const createAnalytics = () => new Analytics({ writeKey: '', - }) - .on('error', console.error); + }).on('error', console.error); module.exports.handler = async (event) => { - ... - // we need to await before returning, otherwise the lambda will exit before sending the request. - await new Promise((resolve) => - analytics().track({ ... }, resolve) - ) + const analytics = createAnalytics() + + analytics.identify({ ... }) + analytics.track({ ... }) + + // ensure analytics events get sent before program exits + await analytics.flush() - ... return { statusCode: 200, }; @@ -99,48 +97,56 @@ module.exports.handler = async (event) => { ``` ### Usage in Vercel Edge Functions + ```ts import { Analytics } from '@segment/analytics-node'; import { NextRequest, NextResponse } from 'next/server'; -export const analytics = new Analytics({ +const createAnalytics = () => new Analytics({ writeKey: '', - flushAt: 1, -}) - .on('error', console.error) +}).on('error', console.error) export const config = { runtime: 'edge', }; export default async (req: NextRequest) => { - await new Promise((resolve) => - analytics.track({ ... }, resolve) - ); + const analytics = createAnalytics() + + analytics.identify({ ... }) + analytics.track({ ... }) + + // ensure analytics events get sent before program exits + await analytics.flush() + return NextResponse.json({ ... }) }; ``` ### Usage in Cloudflare Workers + ```ts import { Analytics, Context } from '@segment/analytics-node'; + +const createAnalytics = () => new Analytics({ + writeKey: '', +}).on('error', console.error); + export default { async fetch( request: Request, env: Env, ctx: ExecutionContext ): Promise { - const analytics = new Analytics({ - flushAt: 1, - writeKey: '', - }).on('error', console.error); + const analytics = createAnalytics() - await new Promise((resolve, reject) => - analytics.track({ ... }, resolve) - ); + analytics.identify({ ... }) + analytics.track({ ... }) + + // ensure analytics events get sent before program exits + await analytics.flush() - ... return new Response(...) }, }; @@ -167,10 +173,7 @@ const settings: OAuthSettings = { const analytics = new Analytics({ writeKey: '', oauthSettings: settings, -}) - -analytics.on('error', (err) => { console.error(err) }) +}).on('error', console.error) analytics.track({ userId: 'foo', event: 'bar' }) - ``` From a963b99ef40bb412573e0f9ff18c0f23399c16f5 Mon Sep 17 00:00:00 2001 From: Seth Silesky <5115498+silesky@users.noreply.github.com> Date: Thu, 2 Jan 2025 12:15:37 -0600 Subject: [PATCH 2/2] wip --- packages/node/README.md | 118 +--------------------------------------- 1 file changed, 1 insertion(+), 117 deletions(-) diff --git a/packages/node/README.md b/packages/node/README.md index 7153a103c..530bc6e39 100644 --- a/packages/node/README.md +++ b/packages/node/README.md @@ -54,126 +54,10 @@ app.post('/cart', (req, res) => { res.sendStatus(201) }); ``` +See our [official documentation](https://segment.com/docs/connections/sources/catalog/libraries/server/node) for more examples and information. ## Settings & Configuration See the documentation: https://segment.com/docs/connections/sources/catalog/libraries/server/node/#configuration You can also see the complete list of settings in the [AnalyticsSettings interface](src/app/settings.ts). - - -## Plugin Architecture -- See segment's [documentation for plugin architecture](https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#plugin-architecture). - - - -## Usage in non-node runtimes -### Usage in AWS Lambda -- [AWS lambda execution environment](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html) is challenging for typically non-response-blocking async activites like tracking or logging, since the runtime terminates / freezes after a response is emitted. - -Here is an example of using analytics.js within a handler: -```ts -const { Analytics } = require('@segment/analytics-node'); - - // Preferable to create a new analytics instance per-invocation. Otherwise, we may get a warning about overlapping flush calls. Also, custom plugins have the potential to be stateful, so we prevent those kind of race conditions. -const createAnalytics = () => new Analytics({ - writeKey: '', - }).on('error', console.error); - -module.exports.handler = async (event) => { - const analytics = createAnalytics() - - analytics.identify({ ... }) - analytics.track({ ... }) - - // ensure analytics events get sent before program exits - await analytics.flush() - - return { - statusCode: 200, - }; - .... -}; -``` - -### Usage in Vercel Edge Functions - -```ts -import { Analytics } from '@segment/analytics-node'; -import { NextRequest, NextResponse } from 'next/server'; - -const createAnalytics = () => new Analytics({ - writeKey: '', -}).on('error', console.error) - -export const config = { - runtime: 'edge', -}; - -export default async (req: NextRequest) => { - const analytics = createAnalytics() - - analytics.identify({ ... }) - analytics.track({ ... }) - - // ensure analytics events get sent before program exits - await analytics.flush() - - return NextResponse.json({ ... }) -}; -``` - -### Usage in Cloudflare Workers - -```ts -import { Analytics, Context } from '@segment/analytics-node'; - - -const createAnalytics = () => new Analytics({ - writeKey: '', -}).on('error', console.error); - -export default { - async fetch( - request: Request, - env: Env, - ctx: ExecutionContext - ): Promise { - const analytics = createAnalytics() - - analytics.identify({ ... }) - analytics.track({ ... }) - - // ensure analytics events get sent before program exits - await analytics.flush() - - return new Response(...) - }, -}; - -``` - -### OAuth 2 -In order to guarantee authorized communication between your server environment and Segment's Tracking API, you can [enable OAuth 2 in your Segment workspace](https://segment.com/docs/partners/enable-with-segment/). To support the non-interactive server environment, the OAuth workflow used is a signed client assertion JWT. You will need a public and private key pair where the public key is uploaded to the segment dashboard and the private key is kept in your server environment to be used by this SDK. Your server will verify its identity by signing a token request and will receive a token that is used to to authorize all communication with the Segment Tracking API. - -You will also need to provide the OAuth Application ID and the public key's ID, both of which are provided in the Segment dashboard. You should ensure that you are implementing handling for Analytics SDK errors. Good logging will help distinguish any configuration issues. - -```ts -import { Analytics, OAuthSettings } from '@segment/analytics-node'; -import { readFileSync } from 'fs' - -const privateKey = readFileSync('private.pem', 'utf8') - -const settings: OAuthSettings = { - clientId: '', - clientKey: privateKey, - keyId: '', -} - -const analytics = new Analytics({ - writeKey: '', - oauthSettings: settings, -}).on('error', console.error) - -analytics.track({ userId: 'foo', event: 'bar' }) -```