or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ai-service-integrations.mdcontext-management.mddatabase-integrations.mderror-capture.mdfeature-flags-integrations.mdframework-integrations.mdindex.mdinitialization.mdmonitoring-sessions.mdnodejs-integrations.mdperformance-monitoring.md

context-management.mddocs/

0

# Context and Scope Management

1

2

Functions for managing context data, user information, tags, and scopes throughout your application.

3

4

## Capabilities

5

6

### User Context

7

8

Set and manage user information for error tracking.

9

10

```typescript { .api }

11

/**

12

* Set user information for the current scope

13

* @param user - User object with identification and metadata

14

*/

15

function setUser(user: User): void;

16

```

17

18

**Usage Examples:**

19

20

```typescript

21

import * as Sentry from "@sentry/node";

22

23

// Set basic user information

24

Sentry.setUser({

25

id: "123",

26

email: "user@example.com",

27

});

28

29

// Set comprehensive user information

30

Sentry.setUser({

31

id: "user-456",

32

username: "johndoe",

33

email: "john.doe@example.com",

34

ip_address: "127.0.0.1",

35

segment: "premium",

36

subscription: "pro",

37

company: "Acme Corp",

38

role: "admin",

39

});

40

41

// Clear user information

42

Sentry.setUser(null);

43

```

44

45

### Tags

46

47

Add tags for filtering and searching events.

48

49

```typescript { .api }

50

/**

51

* Set a single tag for the current scope

52

* @param key - Tag key

53

* @param value - Tag value (must be primitive)

54

*/

55

function setTag(key: string, value: Primitive): void;

56

57

/**

58

* Set multiple tags for the current scope

59

* @param tags - Object containing key-value pairs of tags

60

*/

61

function setTags(tags: { [key: string]: Primitive }): void;

62

```

63

64

**Usage Examples:**

65

66

```typescript

67

import * as Sentry from "@sentry/node";

68

69

// Set individual tags

70

Sentry.setTag("component", "payment");

71

Sentry.setTag("version", "1.2.3");

72

Sentry.setTag("feature_flag", "new_checkout");

73

74

// Set multiple tags at once

75

Sentry.setTags({

76

environment: "production",

77

server: "web-01",

78

region: "us-east-1",

79

build: "build-456",

80

});

81

```

82

83

### Context Data

84

85

Set structured context data for events.

86

87

```typescript { .api }

88

/**

89

* Set context data for the current scope

90

* @param key - Context key/namespace

91

* @param context - Context data object

92

*/

93

function setContext(key: string, context: Context): void;

94

```

95

96

**Usage Examples:**

97

98

```typescript

99

import * as Sentry from "@sentry/node";

100

101

// Set application context

102

Sentry.setContext("app", {

103

name: "my-node-app",

104

version: "1.0.0",

105

build: "123",

106

});

107

108

// Set device/runtime context

109

Sentry.setContext("runtime", {

110

name: "node",

111

version: process.version,

112

platform: process.platform,

113

arch: process.arch,

114

});

115

116

// Set business context

117

Sentry.setContext("order", {

118

id: "order-789",

119

total: 99.99,

120

currency: "USD",

121

items: 3,

122

customer_tier: "premium",

123

});

124

125

// Set custom context

126

Sentry.setContext("feature_flags", {

127

new_ui: true,

128

beta_feature: false,

129

experimental_api: true,

130

});

131

```

132

133

### Extra Data

134

135

Add unstructured extra data to events.

136

137

```typescript { .api }

138

/**

139

* Set extra data for the current scope

140

* @param key - Extra data key

141

* @param extra - Extra data value (can be any type)

142

*/

143

function setExtra(key: string, extra: Extra): void;

144

145

/**

146

* Set multiple extra data values for the current scope

147

* @param extras - Object containing key-value pairs of extra data

148

*/

149

function setExtras(extras: Extras): void;

150

```

151

152

**Usage Examples:**

153

154

```typescript

155

import * as Sentry from "@sentry/node";

156

157

// Set individual extra data

158

Sentry.setExtra("request_id", "req-123456");

159

Sentry.setExtra("user_preferences", userPrefs);

160

Sentry.setExtra("debug_info", {

161

memory_usage: process.memoryUsage(),

162

uptime: process.uptime(),

163

});

164

165

// Set multiple extra values

166

Sentry.setExtras({

167

api_response: apiResponse,

168

processing_time: processingTime,

169

cache_hit: true,

170

batch_size: 50,

171

});

172

```

173

174

### Performance Measurements

175

176

Set custom performance measurements.

177

178

```typescript { .api }

179

/**

180

* Set a performance measurement

181

* @param name - Measurement name

182

* @param value - Measurement value

183

* @param unit - Measurement unit (optional)

184

*/

185

function setMeasurement(name: string, value: number, unit?: MeasurementUnit): void;

186

```

187

188

**Usage Examples:**

189

190

```typescript

191

import * as Sentry from "@sentry/node";

192

193

// Set timing measurements

194

Sentry.setMeasurement("database_query_time", 145, "millisecond");

195

Sentry.setMeasurement("file_processing_time", 2.5, "second");

196

197

// Set size measurements

198

Sentry.setMeasurement("payload_size", 1024, "byte");

199

Sentry.setMeasurement("memory_used", 512, "megabyte");

200

201

// Set count measurements

202

Sentry.setMeasurement("processed_records", 1000);

203

Sentry.setMeasurement("cache_hits", 85);

204

```

205

206

### Scope Management

207

208

Manage and isolate context using scopes.

209

210

```typescript { .api }

211

/**

212

* Get the current scope

213

* @returns Current scope instance

214

*/

215

function getCurrentScope(): Scope;

216

217

/**

218

* Get the isolation scope

219

* @returns Isolation scope instance

220

*/

221

function getIsolationScope(): Scope;

222

223

/**

224

* Get the global scope

225

* @returns Global scope instance

226

*/

227

function getGlobalScope(): Scope;

228

229

/**

230

* Execute a callback with a new scope

231

* @param callback - Function to execute with the new scope

232

* @returns Return value of the callback

233

*/

234

function withScope<T>(callback: (scope: Scope) => T): T;

235

236

/**

237

* Execute a callback with a new isolation scope

238

* @param callback - Function to execute with the new isolation scope

239

* @returns Return value of the callback

240

*/

241

function withIsolationScope<T>(callback: (scope: Scope) => T): T;

242

```

243

244

**Usage Examples:**

245

246

```typescript

247

import * as Sentry from "@sentry/node";

248

249

// Work with current scope

250

const scope = Sentry.getCurrentScope();

251

scope.setTag("component", "user-service");

252

scope.setLevel("warning");

253

254

// Use withScope for isolated context

255

function processUser(user) {

256

return Sentry.withScope((scope) => {

257

scope.setUser(user);

258

scope.setTag("operation", "user-processing");

259

scope.setContext("processing", {

260

startTime: Date.now(),

261

userId: user.id,

262

});

263

264

try {

265

return performUserProcessing(user);

266

} catch (error) {

267

// Error will include the scope context set above

268

Sentry.captureException(error);

269

throw error;

270

}

271

});

272

}

273

274

// Use isolation scope for request-level context

275

function handleRequest(req, res, next) {

276

Sentry.withIsolationScope((scope) => {

277

scope.setTag("request_id", req.id);

278

scope.setUser({ id: req.user?.id });

279

scope.setContext("request", {

280

method: req.method,

281

url: req.url,

282

userAgent: req.headers["user-agent"],

283

});

284

285

next();

286

});

287

}

288

```

289

290

### Scope Manipulation

291

292

Direct scope manipulation methods.

293

294

```typescript { .api }

295

/**

296

* Clear all context data from the current scope

297

*/

298

function clearScope(): void;

299

300

/**

301

* Push a new scope onto the scope stack

302

* @returns New scope instance

303

*/

304

function pushScope(): Scope;

305

306

/**

307

* Pop the current scope from the scope stack

308

*/

309

function popScope(): void;

310

```

311

312

**Usage Examples:**

313

314

```typescript

315

import * as Sentry from "@sentry/node";

316

317

// Clear all scope data

318

Sentry.setUser({ id: "123" });

319

Sentry.setTag("component", "test");

320

Sentry.clearScope(); // All context cleared

321

322

// Manual scope stack management

323

const originalScope = Sentry.pushScope();

324

Sentry.setTag("temporary", "true");

325

// ... do work with temporary context

326

Sentry.popScope(); // Back to original scope

327

```

328

329

## Types

330

331

### User Type

332

333

```typescript { .api }

334

interface User {

335

/** Unique identifier for the user */

336

id?: string;

337

/** Username */

338

username?: string;

339

/** Email address */

340

email?: string;

341

/** IP address */

342

ip_address?: string;

343

/** User segment/group */

344

segment?: string;

345

/** Additional user properties */

346

[key: string]: any;

347

}

348

```

349

350

### Context Types

351

352

```typescript { .api }

353

type Context = { [key: string]: any };

354

type Extra = any;

355

type Extras = { [key: string]: Extra };

356

type Primitive = string | number | boolean | null | undefined;

357

358

interface MeasurementUnit {

359

/** Unit name (e.g., "millisecond", "byte", "count") */

360

unit: string;

361

}

362

```

363

364

### Scope Interface

365

366

```typescript { .api }

367

interface Scope {

368

/** Add a breadcrumb to this scope */

369

addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): Scope;

370

371

/** Set user information for this scope */

372

setUser(user: User | null): Scope;

373

374

/** Set a tag for this scope */

375

setTag(key: string, value: Primitive): Scope;

376

377

/** Set multiple tags for this scope */

378

setTags(tags: { [key: string]: Primitive }): Scope;

379

380

/** Set context data for this scope */

381

setContext(key: string, context: Context | null): Scope;

382

383

/** Set extra data for this scope */

384

setExtra(key: string, extra: Extra): Scope;

385

386

/** Set multiple extra values for this scope */

387

setExtras(extras: Extras): Scope;

388

389

/** Set the severity level for this scope */

390

setLevel(level: SeverityLevel): Scope;

391

392

/** Set the fingerprint for this scope */

393

setFingerprint(fingerprint: string[]): Scope;

394

395

/** Clear all data from this scope */

396

clear(): Scope;

397

398

/** Add an event processor to this scope */

399

addEventProcessor(callback: EventProcessor): Scope;

400

401

/** Update scope data with a callback function */

402

update<T>(updater: (scope: Scope) => T): T;

403

404

/** Clone this scope */

405

clone(): Scope;

406

}

407

```

408

409

### Event Processor

410

411

```typescript { .api }

412

type EventProcessor = (event: Event, hint?: EventHint) => Event | null | PromiseLike<Event | null>;

413

```