Manage contextual data for events using Sentry’s scope system
Sentry uses a three-tier scope system to manage contextual data: Global Scope, Isolation Scope, and Current Scope. Understanding these scopes is essential for properly organizing your error tracking.
Data from all three scopes is merged when an event is sent. More specific scopes override less specific ones: Current Scope > Isolation Scope > Global Scope.
Create a new isolation scope for separate execution contexts:
Sentry.withIsolationScope((isolationScope) => { isolationScope.setUser({ id: 'user-123', email: '[email protected]' }); isolationScope.setTag('tenant', 'acme-corp'); // All operations here share this isolation scope doWork();});
Using withIsolationScope() in environments without an async context strategy (like browsers) may lead to unexpected behavior. This function is primarily designed for server-side environments.
Sentry.setUser({ id: 'user-123', email: '[email protected]', username: 'john_doe', ip_address: '{{auto}}' // Use 'auto' for automatic IP detection});// Clear user dataSentry.setUser(null);
// Set a single tagSentry.setTag('environment', 'production');// Set multiple tagsSentry.setTags({ environment: 'production', version: '2.1.0', feature: 'checkout'});// Unset a tagSentry.setTag('feature', undefined);
Extra data provides additional context (not searchable):
// Set a single extra fieldSentry.setExtra('cart_items', [ { id: 1, name: 'Product A' }, { id: 2, name: 'Product B' }]);// Set multiple extra fieldsSentry.setExtras({ cart_total: 149.98, shipping_method: 'express', coupon_code: 'SAVE10'});
Attributes are applied to logs and metrics (and spans in the future):
import { getCurrentScope } from '@sentry/browser';const scope = getCurrentScope();// Set attributesscope.setAttributes({ is_admin: true, payment_selection: 'credit_card', render_duration: { value: 250, unit: 'ms' }});// Set a single attributescope.setAttribute('user_role', 'admin');// Remove an attributescope.removeAttribute('user_role');
Currently, only strings, numbers, and boolean attributes are fully supported. More complex types will be added in future versions.