0
# Configuration
1
2
Comprehensive configuration options for customizing Langfuse client behavior including authentication, networking, persistence, sampling, and performance tuning.
3
4
## Capabilities
5
6
### Client Initialization
7
8
Initialize the Langfuse client with configuration options.
9
10
```typescript { .api }
11
class Langfuse {
12
/**
13
* Creates a Langfuse client instance
14
* @param params - Configuration including authentication and options
15
*/
16
constructor(params?: {
17
publicKey?: string;
18
secretKey?: string;
19
} & LangfuseOptions);
20
}
21
22
class LangfuseWeb {
23
/**
24
* Creates a web-only Langfuse client (no secret key required)
25
* @param params - Configuration without secretKey
26
*/
27
constructor(params?: Omit<LangfuseOptions, "secretKey">);
28
}
29
```
30
31
**Usage Example:**
32
33
```typescript
34
import { Langfuse, LangfuseWeb } from 'langfuse';
35
36
// Full client with all options
37
const langfuse = new Langfuse({
38
publicKey: 'pk-lf-...',
39
secretKey: 'sk-lf-...',
40
baseUrl: 'https://cloud.langfuse.com',
41
flushAt: 10,
42
flushInterval: 5000,
43
requestTimeout: 10000,
44
enabled: true
45
});
46
47
// Web client (browser-only, no secret key)
48
const langfuseWeb = new LangfuseWeb({
49
publicKey: 'pk-lf-...',
50
persistence: 'localStorage',
51
enabled: true
52
});
53
```
54
55
### Configuration Options
56
57
Complete configuration interface for the Langfuse client.
58
59
```typescript { .api }
60
interface LangfuseOptions {
61
/** Persistence strategy (browser/web environments) */
62
persistence?: "localStorage" | "sessionStorage" | "cookie" | "memory";
63
/** Custom name for persistence storage key */
64
persistence_name?: string;
65
/** Enable/disable tracing globally (default: true) */
66
enabled?: boolean;
67
/** Base URL for Langfuse API (default: https://cloud.langfuse.com) */
68
baseUrl?: string;
69
/** Number of events before auto-flush (default: 15) */
70
flushAt?: number;
71
/** Flush interval in milliseconds (default: 10000) */
72
flushInterval?: number;
73
/** Request timeout in milliseconds (default: 5000) */
74
requestTimeout?: number;
75
/** Release version identifier */
76
release?: string;
77
/** Environment name (e.g., production, staging) */
78
environment?: string;
79
/** Function to mask sensitive data in events */
80
mask?: MaskFunction;
81
/** Sampling rate 0-1 (1 = 100%, 0.1 = 10%) */
82
sampleRate?: number;
83
/** Number of retries for failed requests (default: 3) */
84
fetchRetryCount?: number;
85
/** Retry delay in milliseconds (default: 3000) */
86
fetchRetryDelay?: number;
87
/** SDK integration identifier */
88
sdkIntegration?: string;
89
/** Additional HTTP headers for API requests */
90
additionalHeaders?: Record<string, string>;
91
}
92
93
type MaskFunction = (params: { data: any }) => any;
94
```
95
96
### Authentication
97
98
Configure authentication keys for Langfuse API access.
99
100
```typescript { .api }
101
interface AuthenticationConfig {
102
/** Public key for authentication (required) */
103
publicKey?: string;
104
/** Secret key for authentication (required for server-side) */
105
secretKey?: string;
106
}
107
```
108
109
**Usage Example:**
110
111
```typescript
112
// From constructor
113
const langfuse = new Langfuse({
114
publicKey: 'pk-lf-1234567890abcdef',
115
secretKey: 'sk-lf-1234567890abcdef'
116
});
117
118
// From environment variables
119
// LANGFUSE_PUBLIC_KEY=pk-lf-...
120
// LANGFUSE_SECRET_KEY=sk-lf-...
121
const langfuse2 = new Langfuse();
122
```
123
124
**Environment Variables:**
125
- `LANGFUSE_PUBLIC_KEY`: Public API key
126
- `LANGFUSE_SECRET_KEY`: Secret API key
127
- `LANGFUSE_BASEURL`: Custom base URL
128
- `LANGFUSE_SAMPLE_RATE`: Default sampling rate
129
- `LANGFUSE_TRACING_ENVIRONMENT`: Default environment name
130
131
### Network Configuration
132
133
Configure API endpoints and network behavior.
134
135
```typescript { .api }
136
interface NetworkConfig {
137
/** Base URL for Langfuse API (default: https://cloud.langfuse.com) */
138
baseUrl?: string;
139
/** Request timeout in milliseconds (default: 5000) */
140
requestTimeout?: number;
141
/** Number of retries for failed requests (default: 3) */
142
fetchRetryCount?: number;
143
/** Retry delay in milliseconds (default: 3000) */
144
fetchRetryDelay?: number;
145
/** Additional HTTP headers for API requests */
146
additionalHeaders?: Record<string, string>;
147
}
148
```
149
150
**Usage Example:**
151
152
```typescript
153
const langfuse = new Langfuse({
154
publicKey: 'pk-lf-...',
155
secretKey: 'sk-lf-...',
156
// Self-hosted instance
157
baseUrl: 'https://langfuse.company.com',
158
// Longer timeout for slow networks
159
requestTimeout: 15000,
160
// More aggressive retries
161
fetchRetryCount: 5,
162
fetchRetryDelay: 5000,
163
// Custom headers
164
additionalHeaders: {
165
'X-Custom-Header': 'value',
166
'X-Environment': 'production'
167
}
168
});
169
```
170
171
### Batching and Flushing
172
173
Configure event batching and automatic flushing behavior.
174
175
```typescript { .api }
176
interface BatchingConfig {
177
/** Number of events before auto-flush (default: 15) */
178
flushAt?: number;
179
/** Flush interval in milliseconds (default: 10000) */
180
flushInterval?: number;
181
}
182
```
183
184
**Usage Example:**
185
186
```typescript
187
// Aggressive flushing (low latency, more network calls)
188
const lowLatency = new Langfuse({
189
publicKey: 'pk-lf-...',
190
secretKey: 'sk-lf-...',
191
flushAt: 1, // Flush after every event
192
flushInterval: 1000 // Flush every second
193
});
194
195
// Conservative batching (high throughput, fewer network calls)
196
const highThroughput = new Langfuse({
197
publicKey: 'pk-lf-...',
198
secretKey: 'sk-lf-...',
199
flushAt: 100, // Batch up to 100 events
200
flushInterval: 30000 // Flush every 30 seconds
201
});
202
203
// Balanced (default)
204
const balanced = new Langfuse({
205
publicKey: 'pk-lf-...',
206
secretKey: 'sk-lf-...',
207
flushAt: 15,
208
flushInterval: 10000
209
});
210
```
211
212
### Persistence Configuration
213
214
Configure data persistence for browser environments.
215
216
```typescript { .api }
217
interface PersistenceConfig {
218
/** Persistence strategy */
219
persistence?: "localStorage" | "sessionStorage" | "cookie" | "memory";
220
/** Custom name for persistence storage key */
221
persistence_name?: string;
222
}
223
```
224
225
**Usage Example:**
226
227
```typescript
228
// Use localStorage (survives page refresh)
229
const persistent = new LangfuseWeb({
230
publicKey: 'pk-lf-...',
231
persistence: 'localStorage',
232
persistence_name: 'my-app' // Key: lf_my-app_langfuse
233
});
234
235
// Use sessionStorage (cleared on tab close)
236
const session = new LangfuseWeb({
237
publicKey: 'pk-lf-...',
238
persistence: 'sessionStorage'
239
});
240
241
// Use memory only (cleared on page refresh)
242
const memory = new LangfuseWeb({
243
publicKey: 'pk-lf-...',
244
persistence: 'memory'
245
});
246
247
// Use cookies
248
const cookie = new LangfuseWeb({
249
publicKey: 'pk-lf-...',
250
persistence: 'cookie'
251
});
252
```
253
254
### Sampling Configuration
255
256
Configure trace sampling to reduce data volume.
257
258
```typescript { .api }
259
interface SamplingConfig {
260
/** Sampling rate 0-1 (1 = 100%, 0.1 = 10%, 0 = disabled) */
261
sampleRate?: number;
262
}
263
```
264
265
**Usage Example:**
266
267
```typescript
268
// Sample 10% of traces
269
const sampled = new Langfuse({
270
publicKey: 'pk-lf-...',
271
secretKey: 'sk-lf-...',
272
sampleRate: 0.1
273
});
274
275
// Sample 50% of traces
276
const halfSampled = new Langfuse({
277
publicKey: 'pk-lf-...',
278
secretKey: 'sk-lf-...',
279
sampleRate: 0.5
280
});
281
282
// No sampling (100% of traces)
283
const fullTracing = new Langfuse({
284
publicKey: 'pk-lf-...',
285
secretKey: 'sk-lf-...',
286
sampleRate: 1.0
287
});
288
```
289
290
### Data Masking
291
292
Configure sensitive data masking for privacy compliance.
293
294
```typescript { .api }
295
type MaskFunction = (params: { data: any }) => any;
296
297
interface MaskingConfig {
298
/** Function to mask sensitive data in events */
299
mask?: MaskFunction;
300
}
301
```
302
303
**Usage Example:**
304
305
```typescript
306
// Mask email addresses and API keys
307
const langfuse = new Langfuse({
308
publicKey: 'pk-lf-...',
309
secretKey: 'sk-lf-...',
310
mask: ({ data }) => {
311
// Deep clone to avoid modifying original
312
const masked = JSON.parse(JSON.stringify(data));
313
314
// Mask function to recursively process object
315
const maskSensitiveData = (obj: any): any => {
316
if (typeof obj === 'string') {
317
// Mask email addresses
318
obj = obj.replace(/[\w.-]+@[\w.-]+\.\w+/g, '[EMAIL]');
319
// Mask API keys
320
obj = obj.replace(/sk-[a-zA-Z0-9]{32,}/g, '[API_KEY]');
321
// Mask credit card numbers
322
obj = obj.replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g, '[CARD]');
323
return obj;
324
}
325
326
if (Array.isArray(obj)) {
327
return obj.map(maskSensitiveData);
328
}
329
330
if (obj && typeof obj === 'object') {
331
const result: any = {};
332
for (const key in obj) {
333
// Mask specific fields
334
if (['password', 'apiKey', 'secretKey', 'token'].includes(key)) {
335
result[key] = '[REDACTED]';
336
} else {
337
result[key] = maskSensitiveData(obj[key]);
338
}
339
}
340
return result;
341
}
342
343
return obj;
344
};
345
346
return maskSensitiveData(masked);
347
}
348
});
349
350
// Usage
351
const trace = langfuse.trace({
352
name: 'user-action',
353
input: {
354
email: 'user@example.com',
355
apiKey: 'sk-1234567890abcdef',
356
message: 'Contact me at john.doe@company.com'
357
}
358
});
359
// Stored as: { email: '[EMAIL]', apiKey: '[API_KEY]', message: 'Contact me at [EMAIL]' }
360
```
361
362
### Environment Configuration
363
364
Tag traces with environment and release information.
365
366
```typescript { .api }
367
interface EnvironmentConfig {
368
/** Environment name (e.g., production, staging, development) */
369
environment?: string;
370
/** Release version identifier */
371
release?: string;
372
}
373
```
374
375
**Usage Example:**
376
377
```typescript
378
// Tag all traces with environment
379
const langfuse = new Langfuse({
380
publicKey: 'pk-lf-...',
381
secretKey: 'sk-lf-...',
382
environment: 'production',
383
release: 'v1.2.3'
384
});
385
386
// Traces automatically include environment/release
387
const trace = langfuse.trace({
388
name: 'user-action'
389
// environment: 'production' and release: 'v1.2.3' are auto-added
390
});
391
392
// Override per trace
393
const devTrace = langfuse.trace({
394
name: 'test-action',
395
environment: 'development' // Overrides config
396
});
397
```
398
399
### Feature Flags
400
401
Enable or disable tracing globally.
402
403
```typescript { .api }
404
interface FeatureConfig {
405
/** Enable/disable tracing globally (default: true) */
406
enabled?: boolean;
407
}
408
```
409
410
**Usage Example:**
411
412
```typescript
413
// Disable tracing in development
414
const langfuse = new Langfuse({
415
publicKey: 'pk-lf-...',
416
secretKey: 'sk-lf-...',
417
enabled: process.env.NODE_ENV === 'production'
418
});
419
420
// No events are sent when enabled=false
421
const trace = langfuse.trace({ name: 'test' }); // No-op
422
await langfuse.flushAsync(); // No-op
423
424
// Toggle at runtime
425
langfuse.debug(false); // Disable
426
langfuse.debug(true); // Enable
427
```
428
429
### SDK Integration
430
431
Identify SDK integrations for analytics.
432
433
```typescript { .api }
434
interface IntegrationConfig {
435
/** SDK integration identifier */
436
sdkIntegration?: string;
437
}
438
```
439
440
**Usage Example:**
441
442
```typescript
443
const langfuse = new Langfuse({
444
publicKey: 'pk-lf-...',
445
secretKey: 'sk-lf-...',
446
sdkIntegration: 'langchain' // Identifies usage from Langchain
447
});
448
```
449
450
## Configuration from Environment Variables
451
452
Langfuse automatically reads configuration from environment variables if not provided in the constructor.
453
454
```typescript { .api }
455
/**
456
* Configures Langfuse SDK with environment variables
457
* @param params - Optional override parameters
458
* @param secretRequired - Whether secret key is required (default: true)
459
* @returns Merged configuration
460
*/
461
function configLangfuseSDK(
462
params?: LangfuseCoreOptions,
463
secretRequired?: boolean
464
): LangfuseCoreOptions;
465
```
466
467
**Supported Environment Variables:**
468
- `LANGFUSE_PUBLIC_KEY`: Public API key
469
- `LANGFUSE_SECRET_KEY`: Secret API key
470
- `LANGFUSE_BASEURL`: Custom base URL
471
- `LANGFUSE_SAMPLE_RATE`: Sampling rate (0-1)
472
- `LANGFUSE_TRACING_ENVIRONMENT`: Environment name
473
- `LANGFUSE_RELEASE`: Release version
474
- `LANGFUSE_ENABLED`: Enable/disable tracing (true/false)
475
476
**Usage Example:**
477
478
```bash
479
# .env file
480
LANGFUSE_PUBLIC_KEY=pk-lf-1234567890
481
LANGFUSE_SECRET_KEY=sk-lf-1234567890
482
LANGFUSE_BASEURL=https://cloud.langfuse.com
483
LANGFUSE_SAMPLE_RATE=0.1
484
LANGFUSE_TRACING_ENVIRONMENT=production
485
LANGFUSE_RELEASE=v1.2.3
486
LANGFUSE_ENABLED=true
487
```
488
489
```typescript
490
import { Langfuse } from 'langfuse';
491
492
// Reads all config from environment
493
const langfuse = new Langfuse();
494
495
// Override specific values
496
const override = new Langfuse({
497
flushAt: 5, // Override batching
498
// Other values from environment
499
});
500
```
501
502
## Complete Configuration Examples
503
504
### Production Configuration
505
506
```typescript
507
import { Langfuse } from 'langfuse';
508
509
const langfuse = new Langfuse({
510
publicKey: process.env.LANGFUSE_PUBLIC_KEY,
511
secretKey: process.env.LANGFUSE_SECRET_KEY,
512
baseUrl: 'https://cloud.langfuse.com',
513
514
// Environment
515
environment: 'production',
516
release: process.env.APP_VERSION,
517
518
// Batching (balanced)
519
flushAt: 20,
520
flushInterval: 10000,
521
522
// Network (reliable)
523
requestTimeout: 10000,
524
fetchRetryCount: 5,
525
fetchRetryDelay: 3000,
526
527
// Sampling (10%)
528
sampleRate: 0.1,
529
530
// Masking
531
mask: ({ data }) => {
532
const masked = JSON.parse(JSON.stringify(data));
533
// Mask PII
534
const maskPII = (obj: any): any => {
535
if (typeof obj === 'string') {
536
return obj
537
.replace(/[\w.-]+@[\w.-]+\.\w+/g, '[EMAIL]')
538
.replace(/\b\d{3}-\d{2}-\d{4}\b/g, '[SSN]');
539
}
540
if (Array.isArray(obj)) return obj.map(maskPII);
541
if (obj && typeof obj === 'object') {
542
const result: any = {};
543
for (const key in obj) {
544
if (['password', 'ssn', 'creditCard'].includes(key)) {
545
result[key] = '[REDACTED]';
546
} else {
547
result[key] = maskPII(obj[key]);
548
}
549
}
550
return result;
551
}
552
return obj;
553
};
554
return maskPII(masked);
555
},
556
557
// Headers
558
additionalHeaders: {
559
'X-App-Name': 'my-app',
560
'X-Environment': 'production'
561
}
562
});
563
```
564
565
### Development Configuration
566
567
```typescript
568
import { Langfuse } from 'langfuse';
569
570
const langfuse = new Langfuse({
571
publicKey: 'pk-lf-dev-key',
572
secretKey: 'sk-lf-dev-key',
573
baseUrl: 'http://localhost:3000', // Local Langfuse instance
574
575
// Environment
576
environment: 'development',
577
release: 'dev',
578
579
// Aggressive flushing for testing
580
flushAt: 1,
581
flushInterval: 1000,
582
583
// Network (fast fail)
584
requestTimeout: 2000,
585
fetchRetryCount: 1,
586
fetchRetryDelay: 500,
587
588
// Full sampling
589
sampleRate: 1.0,
590
591
// No masking in development
592
mask: undefined
593
});
594
595
// Enable debug logging
596
langfuse.debug(true);
597
```
598
599
### High-Throughput Configuration
600
601
```typescript
602
import { Langfuse } from 'langfuse';
603
604
const langfuse = new Langfuse({
605
publicKey: process.env.LANGFUSE_PUBLIC_KEY,
606
secretKey: process.env.LANGFUSE_SECRET_KEY,
607
608
// Large batches
609
flushAt: 100,
610
flushInterval: 30000,
611
612
// Aggressive timeouts
613
requestTimeout: 15000,
614
fetchRetryCount: 3,
615
fetchRetryDelay: 5000,
616
617
// Low sampling for high volume
618
sampleRate: 0.01, // 1% sampling
619
620
// Environment
621
environment: 'production',
622
release: process.env.APP_VERSION
623
});
624
```
625
626
### Browser Configuration
627
628
```typescript
629
import { LangfuseWeb } from 'langfuse';
630
631
const langfuse = new LangfuseWeb({
632
publicKey: 'pk-lf-browser-key',
633
634
// Persistence
635
persistence: 'localStorage',
636
persistence_name: 'my-app-analytics',
637
638
// Batching (browser-friendly)
639
flushAt: 5,
640
flushInterval: 5000,
641
642
// Network
643
requestTimeout: 5000,
644
fetchRetryCount: 2,
645
fetchRetryDelay: 2000,
646
647
// Sampling
648
sampleRate: 0.2, // 20% of users
649
650
// Environment
651
environment: 'production'
652
});
653
```
654
655
## Runtime Configuration
656
657
### Debug Mode
658
659
Enable or disable debug logging at runtime.
660
661
```typescript { .api }
662
/**
663
* Enables or disables debug mode
664
* @param enabled - Debug mode state (default: true)
665
*/
666
debug(enabled?: boolean): void;
667
```
668
669
**Usage Example:**
670
671
```typescript
672
const langfuse = new Langfuse();
673
674
// Enable debug logging
675
langfuse.debug(true);
676
677
// Disable debug logging
678
langfuse.debug(false);
679
680
// Toggle based on environment
681
langfuse.debug(process.env.DEBUG === 'true');
682
```
683
684
### Event Listeners
685
686
Register event listeners for lifecycle events.
687
688
```typescript { .api }
689
/**
690
* Registers an event listener
691
* @param event - Event name
692
* @param cb - Callback function
693
* @returns Unsubscribe function
694
*/
695
on(event: string, cb: (...args: any[]) => void): () => void;
696
```
697
698
**Usage Example:**
699
700
```typescript
701
const langfuse = new Langfuse();
702
703
// Listen for flush events
704
const unsubscribe = langfuse.on('flush', (data) => {
705
console.log('Events flushed:', data);
706
});
707
708
// Listen for errors
709
langfuse.on('error', (error) => {
710
console.error('Langfuse error:', error);
711
});
712
713
// Unsubscribe
714
unsubscribe();
715
```
716