setContextValue()

Set a value in the trace context by key

Overview

setContextValue() stores a value in the trace context that can be retrieved by child spans using getContextValue(). Useful for passing data without explicit parameters.

Signature

1setContextValue(key: string, value: any): void

Basic Usage

1import { RespanTelemetry } from '@respan/tracing';
2
3const respanAi = new RespanTelemetry({
4 apiKey: process.env.RESPAN_API_KEY,
5 appName: 'my-app'
6});
7
8await respanAi.initialize();
9
10await respanAi.withWorkflow(
11 { name: 'user_workflow' },
12 async () => {
13 const client = respanAi.getClient();
14
15 // Store user ID in context
16 client.setContextValue('user_id', 'user-123');
17
18 await respanAi.withTask(
19 { name: 'nested_task' },
20 async () => {
21 const userId = client.getContextValue('user_id');
22 console.log(`Processing for: ${userId}`);
23 }
24 );
25
26 return 'complete';
27 }
28);

Request Context

1await respanAi.withWorkflow(
2 { name: 'api_request' },
3 async () => {
4 const client = respanAi.getClient();
5
6 // Store request metadata
7 client.setContextValue('request_id', generateRequestId());
8 client.setContextValue('timestamp', Date.now());
9 client.setContextValue('ip_address', req.ip);
10 client.setContextValue('user_agent', req.headers['user-agent']);
11
12 // All child spans can access this context
13 await processRequest();
14
15 return 'done';
16 }
17);

User Session Context

1await respanAi.withWorkflow(
2 { name: 'user_session' },
3 async () => {
4 const client = respanAi.getClient();
5
6 // Store session info
7 client.setContextValue('session_id', 'SESSION-ABC');
8 client.setContextValue('user_id', 'user-123');
9 client.setContextValue('user_role', 'premium');
10 client.setContextValue('account_tier', 'enterprise');
11
12 await respanAi.withTask(
13 { name: 'load_preferences' },
14 async () => {
15 const userId = client.getContextValue('user_id');
16 return await loadUserPreferences(userId);
17 }
18 );
19
20 await respanAi.withTask(
21 { name: 'check_permissions' },
22 async () => {
23 const role = client.getContextValue('user_role');
24 return await checkPermissions(role);
25 }
26 );
27
28 return 'session_initialized';
29 }
30);

Feature Flags

1await respanAi.withWorkflow(
2 { name: 'feature_enabled_workflow' },
3 async () => {
4 const client = respanAi.getClient();
5
6 // Load and store feature flags
7 const flags = await loadFeatureFlags();
8 client.setContextValue('new_ui_enabled', flags.newUI);
9 client.setContextValue('beta_features', flags.beta);
10 client.setContextValue('experimental_algorithm', flags.experimental);
11
12 await respanAi.withTask(
13 { name: 'render_ui' },
14 async () => {
15 const newUI = client.getContextValue('new_ui_enabled');
16 if (newUI) {
17 return await renderNewUI();
18 } else {
19 return await renderLegacyUI();
20 }
21 }
22 );
23
24 return 'rendered';
25 }
26);

Configuration Propagation

1await respanAi.withWorkflow(
2 { name: 'data_pipeline' },
3 async () => {
4 const client = respanAi.getClient();
5
6 // Store configuration
7 client.setContextValue('batch_size', 100);
8 client.setContextValue('parallel_workers', 4);
9 client.setContextValue('retry_attempts', 3);
10 client.setContextValue('timeout_ms', 5000);
11
12 await respanAi.withTask(
13 { name: 'process_batches' },
14 async () => {
15 const batchSize = client.getContextValue('batch_size');
16 const workers = client.getContextValue('parallel_workers');
17 return await processBatches(batchSize, workers);
18 }
19 );
20
21 return 'complete';
22 }
23);

Dynamic Context Updates

1await respanAi.withWorkflow(
2 { name: 'stateful_workflow' },
3 async () => {
4 const client = respanAi.getClient();
5
6 // Initial state
7 client.setContextValue('current_stage', 'initialization');
8 client.setContextValue('records_processed', 0);
9
10 await respanAi.withTask(
11 { name: 'stage_1' },
12 async () => {
13 client.setContextValue('current_stage', 'processing');
14 const result = await processStage1();
15 client.setContextValue('records_processed', result.count);
16 return result;
17 }
18 );
19
20 await respanAi.withTask(
21 { name: 'stage_2' },
22 async () => {
23 client.setContextValue('current_stage', 'finalization');
24 const previousCount = client.getContextValue('records_processed');
25 const result = await processStage2(previousCount);
26 client.setContextValue('records_processed', previousCount + result.count);
27 return result;
28 }
29 );
30
31 client.setContextValue('current_stage', 'completed');
32
33 return client.getContextValue('records_processed');
34 }
35);

Complex Objects

1await respanAi.withWorkflow(
2 { name: 'order_workflow' },
3 async () => {
4 const client = respanAi.getClient();
5
6 // Store complex objects
7 client.setContextValue('order', {
8 id: 'ORDER-789',
9 customer_id: 'CUST-123',
10 items: [
11 { sku: 'ITEM-1', quantity: 2, price: 29.99 },
12 { sku: 'ITEM-2', quantity: 1, price: 49.99 }
13 ],
14 total: 109.97
15 });
16
17 await respanAi.withTask(
18 { name: 'validate_order' },
19 async () => {
20 const order = client.getContextValue('order');
21 return await validateOrder(order);
22 }
23 );
24
25 await respanAi.withTask(
26 { name: 'calculate_shipping' },
27 async () => {
28 const order = client.getContextValue('order');
29 const shipping = await calculateShipping(order.items);
30 order.shipping = shipping;
31 client.setContextValue('order', order);
32 return shipping;
33 }
34 );
35
36 return 'order_processed';
37 }
38);

Parameters

key
stringRequired

The key to store the value under

value
anyRequired

The value to store (can be any type: string, number, object, array, etc.)

Best Practices

  • Use context for cross-cutting concerns (request IDs, user info, feature flags)
  • Set context early in the workflow for child spans to access
  • Store configuration that multiple tasks need without explicit passing
  • Context values can be updated dynamically as the workflow progresses
  • Context is scoped to the current trace and its child spans
  • Use meaningful key names for clarity
  • Context is useful for avoiding parameter drilling through many function layers