Q7 of 38 · Performance
How do you handle dynamic data like CSRF tokens and session IDs in JMeter?
Short answer
Short answer: Extract values from prior responses with regex/JSON/CSS extractors, store as JMeter variables, then reference them in subsequent requests. Add an HTTP Cookie Manager for session cookies and an HTTP Header Manager for tokens that travel as headers.
Detail
This is JMeter's correlation problem — capturing values that the server generates and the client must echo back on the next request.
Step 1 — Identify the dynamic value. Record the flow with the JMeter HTTP(S) Test Script Recorder or a browser proxy. Look for values that change every login but must match on subsequent requests — CSRF tokens, anti-forgery tokens, JSESSIONIDs, JWTs, encrypted ViewState, ASP.NET __VIEWSTATE.
Step 2 — Choose the right extractor. Add a post-processor under the request that returned the value:
- Regular Expression Extractor — works on any text response.
<input name="csrf" value="([^"]+)">captures into${csrf}. - JSON Extractor — for JSON APIs, JSONPath like
$.tokenis cleaner than regex. - CSS/JQuery Extractor — for HTML pages, CSS selectors are more readable than regex.
- Boundary Extractor — when the response is delimited by literal start/end strings.
Step 3 — Reference the variable. Subsequent samplers use ${csrf} in form parameters or headers. The HTTP Cookie Manager element handles JSESSIONID-style cookies automatically — add it once at thread-group level.
Common gotchas: forgetting that variables are thread-local (each VU gets its own copy — that's correct), forgetting to URL-encode token values that contain + or /, and capturing only the first match when the response has many (use Match No. to pick a specific occurrence). Always add an assertion that the extracted variable is non-empty — silent extraction failures cascade into 100% authentication errors and confusing reports.
// EXAMPLE
csrf-extractor.jmx
<RegexExtractor guiclass="RegexExtractorGui"
testname="Extract CSRF token">
<stringProp name="RegexExtractor.refname">csrf</stringProp>
<stringProp name="RegexExtractor.regex">name="csrf" value="([^"]+)"</stringProp>
<stringProp name="RegexExtractor.template">$1$</stringProp>
<stringProp name="RegexExtractor.match_number">1</stringProp>
<stringProp name="RegexExtractor.default">CSRF_NOT_FOUND</stringProp>
</RegexExtractor>
<!-- Subsequent sampler references it as ${csrf} -->