Screenshot Auth Pages with Rotating CSRF Tokens
In this article
Capturing screenshots of authenticated pages that use rotating CSRF tokens is tricky because the token changes on every request or session, so a simple GET request often returns a login page or an error. This guide shows you how to use a headless browser (like Puppeteer or Playwright) to log in, extract the current token, and use it to navigate and screenshot the protected page reliably.
What You'll Need
- Node.js installed (v14 or later) for Puppeteer/Playwright.
- A working login (username/password) for the site you're testing.
- Basic familiarity with JavaScript and async/await.
- Access to the site's login form (HTML selectors) and the URL of the page you want to screenshot.
Step-by-Step
- Set up your project. Create a new directory, run
npm init -y, then install Puppeteer:npm install puppeteer(orplaywrightif you prefer). - Launch a headless browser. Write a script that starts a browser instance with
puppeteer.launch(). Setheadless: 'new'(orfalsefor debugging). - Open the login page. Use
page.goto('https://example.com/login')and wait for the page to load. - Extract the initial CSRF token. If the token is in a hidden input field, use . If it's in a meta tag or cookie, adjust accordingly. Store it in a variable.
- Fill in the login form. Type the username and password into the appropriate fields using
page.type(). If the form requires the token to be submitted, set the hidden input's value to the token you extracted. - Submit the form. Click the submit button or press Enter. Wait for navigation to complete using
page.waitForNavigation()orpage.waitForSelector()for a post-login element. - Get a fresh CSRF token after login. Many apps rotate the token after authentication. Navigate to a page that contains a new token (often the dashboard), and extract it again using the same method.
- Navigate to the target page. Use
page.goto('https://example.com/protected-page'). If the page requires the token in a header or query parameter, add it. For example, if the token is in a header:page.setExtraHTTPHeaders({'X-CSRF-Token': freshToken})before navigating. - Wait for the page to render. Use
page.waitForSelector('body')or a specific element that indicates the content is loaded. If the page makes AJAX calls, you may need to wait for a network idle:page.waitForNetworkIdle(). - Take the screenshot. Call
page.screenshot({ path: 'screenshot.png', fullPage: true })to capture the full page or a specific viewport. - Close the browser. Use
browser.close()to free resources.
Common Mistakes
- Using the initial token for later requests. The token rotates after login, so always re-extract it after authentication.
- Not waiting for the token to be injected. Some pages load the token via JavaScript after initial HTML. Wait for the input field to have a value before reading it.
- Hardcoding selectors. Selectors change between versions. Use robust selectors like or #csrf-token .
- Ignoring cookies. Ensure the browser session maintains cookies across requests; Puppeteer does this automatically, but if you're using a separate HTTP client, you must manage cookies.
- Not handling multi-page tokens. Some apps use a new token per page load. If you get a 403, re-fetch the token from the target page itself.
Tips
- Use a viewport that matches your target. Set
page.setViewport({ width: 1280, height: 800 })for consistent screenshots. - Add a small delay after navigation. Sometimes a 500ms wait helps ensure all dynamic content is rendered.
- Log the token values. During development, print the token to the console to verify it's changing.
- Use environment variables for credentials. Don't hardcode passwords in your script.
- Consider using Playwright's codegen. It can help you identify selectors by recording your manual login.
Troubleshooting
- Getting a 403 or login redirect. The token is likely stale or missing. Re-extract it from the page you're trying to access, not from the login page.
- Token is empty. The page might load the token via JavaScript after DOMContentLoaded. Use
page.waitForFunctionto wait until the input's value is non-empty. - Login fails. Check if the login form has extra fields (like a captcha) or if the password field is not a standard input. Use
page.screenshot()of the login page to see what's happening. - Screenshot is blank. The page might be loading slowly. Increase the timeout or wait for a specific selector that indicates content is ready.
- Token in a cookie. Some frameworks use a cookie instead of a form field. Read the cookie via
page.cookies()and include it in your requests.
Frequently Asked Questions
Can I use a simple HTTP client like axios instead of a headless browser?
Yes, but you'll need to manually manage cookies and parse the token from HTML. Headless browsers handle session and JavaScript rendering automatically, which is more reliable for complex SPAs.
What if the CSRF token is in a meta tag?
Extract it with and then use it in headers or hidden inputs as needed.
Do I need to rotate the token for every request?
Only if the site requires it. Many sites rotate only after login. Test by making a request with the same token twice; if the second fails, you must re-fetch each time.
How do I handle a token that is generated by JavaScript on the target page?
Navigate to the target page first, extract the token, then if the page requires a token for a subsequent AJAX call, you can use page.evaluate() to make that call within the page context.
Can I take screenshots of multiple pages with the same session?
Yes, keep the same browser page open and navigate to each URL, re-extracting the token if needed.
Is there a way to bypass the token entirely?
No, and trying to bypass security measures is not recommended. The token is there to protect against CSRF attacks; your script should respect it.