Issue
I want to set a tracesSampler sample rate from request data (for example user agent, path, or method), and I do not know where that data lives in samplingContext.
Applies To
All SaaS Customers and Self-Hosted Users
JavaScript SDK version 8 and later
Tracing
Node.js and other server-side JavaScript runtimes (for HTTP request attributes)
Resolution
Use samplingContext.attributes. In JavaScript SDK version 8 and later, tracesSampler receives the span’s initial attributes on that object.
Define
tracesSamplerinSentry.init.Read request fields from
samplingContext.attributes.Return a sample rate between
0and1based on those values.
Example: sample based on the request user agent on a server HTTP span:
Sentry.init({
tracesSampler: (samplingContext) => {
const userAgent = samplingContext.attributes?.["http.user_agent"]; if (userAgent?.includes("HealthChecker")) {
return 0;
} return 0.2;
},
});
For incoming HTTP server spans, initial attributes can include values such as http.user_agent, http.method, and http.target. Custom attributes you pass when starting a span are also available in samplingContext.attributes.
tracesSampler only sees attributes present when the span starts. Attributes set later on the span, such as response status codes, are not available in samplingContext.
See the JavaScript sampling documentation for the full samplingContext shape and more tracesSampler examples.
