@@ -96,9 +96,16 @@ export function init(options: NodeOptions = {}): void {
9696 const detectedRelease = getSentryRelease ( ) ;
9797 if ( detectedRelease !== undefined ) {
9898 options . release = detectedRelease ;
99+ } else {
100+ // If release is not provided, then we should disable autoSessionTracking
101+ options . autoSessionTracking = false ;
99102 }
100103 }
101104
105+ if ( options . autoSessionTracking === undefined ) {
106+ options . autoSessionTracking = true ;
107+ }
108+
102109 if ( options . environment === undefined && process . env . SENTRY_ENVIRONMENT ) {
103110 options . environment = process . env . SENTRY_ENVIRONMENT ;
104111 }
@@ -109,6 +116,10 @@ export function init(options: NodeOptions = {}): void {
109116 }
110117
111118 initAndBind ( NodeClient , options ) ;
119+
120+ if ( options . autoSessionTracking ) {
121+ startSessionTracking ( ) ;
122+ }
112123}
113124
114125/**
@@ -148,6 +159,20 @@ export async function close(timeout?: number): Promise<boolean> {
148159 return Promise . reject ( false ) ;
149160}
150161
162+ /**
163+ * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client
164+ */
165+ export function isAutoSessionTrackingEnabled ( client ?: NodeClient ) : boolean {
166+ if ( client === undefined ) {
167+ return false ;
168+ }
169+ const clientOptions : NodeOptions = client && client . getOptions ( ) ;
170+ if ( clientOptions && clientOptions . autoSessionTracking !== undefined ) {
171+ return clientOptions . autoSessionTracking ;
172+ }
173+ return false ;
174+ }
175+
151176/**
152177 * Returns a release dynamically from environment variables.
153178 */
@@ -180,3 +205,18 @@ export function getSentryRelease(fallback?: string): string | undefined {
180205 fallback
181206 ) ;
182207}
208+
209+ /**
210+ * Enable automatic Session Tracking for the node process.
211+ */
212+ function startSessionTracking ( ) : void {
213+ const hub = getCurrentHub ( ) ;
214+ hub . startSession ( ) ;
215+ // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because
216+ // The 'beforeExit' event is not emitted for conditions causing explicit termination,
217+ // such as calling process.exit() or uncaught exceptions.
218+ // Ref: https://nodejs.org/api/process.html#process_event_beforeexit
219+ process . on ( 'beforeExit' , ( ) => {
220+ hub . endSession ( ) ;
221+ } ) ;
222+ }
0 commit comments