@@ -75,22 +75,16 @@ Here is an example of using analytics.js within a handler:
7575``` ts
7676const { Analytics } = require (' @segment/analytics-node' );
7777
78- // since analytics has the potential to be stateful if there are any plugins added,
79- // to be on the safe side, we should instantiate a new instance of analytics on every request (the cost of instantiation is low).
80- const analytics = () => new Analytics ({
81- flushAt: 1 ,
78+ const analytics = new Analytics ({
8279 writeKey: ' <MY_WRITE_KEY>' ,
8380 })
8481 .on (' error' , console .error );
8582
8683module .exports .handler = async (event ) => {
87- ...
88- // we need to await before returning, otherwise the lambda will exit before sending the request.
89- await new Promise ((resolve ) =>
90- analytics ().track ({ ... }, resolve )
91- )
84+ analytics .track ({ ... })
85+
86+ await analytics .flush ()
9287
93- ...
9488 return {
9589 statusCode: 200 ,
9690 };
@@ -105,7 +99,6 @@ import { NextRequest, NextResponse } from 'next/server';
10599
106100export const analytics = new Analytics ({
107101 writeKey: ' <MY_WRITE_KEY>' ,
108- flushAt: 1 ,
109102})
110103 .on (' error' , console .error )
111104
@@ -114,9 +107,10 @@ export const config = {
114107};
115108
116109export default async (req : NextRequest ) => {
117- await new Promise ((resolve ) =>
118- analytics .track ({ ... }, resolve )
119- );
110+ analytics .track ({ ... })
111+
112+ await analytics .flush ()
113+
120114 return NextResponse .json ({ ... })
121115};
122116```
@@ -125,22 +119,21 @@ export default async (req: NextRequest) => {
125119``` ts
126120import { Analytics , Context } from ' @segment/analytics-node' ;
127121
122+ const analytics = new Analytics ({
123+ writeKey: ' <MY_WRITE_KEY>' ,
124+ }).on (' error' , console .error );
125+
128126export default {
129127 async fetch(
130128 request : Request ,
131129 env : Env ,
132130 ctx : ExecutionContext
133131 ): Promise <Response > {
134- const analytics = new Analytics ({
135- flushAt: 1 ,
136- writeKey: ' <MY_WRITE_KEY>' ,
137- }).on (' error' , console .error );
138132
139- await new Promise (( resolve , reject ) =>
140- analytics . track ({ ... }, resolve )
141- );
133+ analytics . track ({ ... })
134+
135+ await analytics . flush ()
142136
143- ...
144137 return new Response (... )
145138 },
146139};
0 commit comments