Trace Redirects with Headless Chrome DevTools Guide
In this article
Tracing every redirect with Headless Chrome DevTools allows you to capture the full chain of HTTP responses—including 301 and 302 status codes—that occur between the initial request and the final destination page. This is essential for debugging SEO redirect loops, analyzing affiliate link hops, and auditing security headers across multiple jumps. By leveraging the Chrome DevTools Protocol (CDP), you can intercept network events in a headless environment where a standard browser window is not visible.
What You'll Need
- Node.js installed on your system.
- Puppeteer or Playwright (libraries used to control Headless Chrome).
- A terminal or command-line interface.
- Basic knowledge of JavaScript (async/await syntax).
Step-by-Step
- Initialize Your Project: Create a new directory for your project and initialize it using
npm init -y. This sets up the environment for installing the necessary automation libraries. - Install Puppeteer: Run
npm install puppeteerin your terminal. Puppeteer is the most common library for controlling Headless Chrome via the DevTools Protocol, providing a high-level API to interact with the browser. - Launch the Browser: Create a JavaScript file (e.g.,
trace.js). Start by importing Puppeteer and launching the browser instance. Setheadless: trueto ensure it runs in the background. - Create a New Page: Open a new browser tab using
browser.newPage(). This page object will be the primary interface for monitoring network requests. - Enable Network Request Monitoring: Use the
page.on('request』andpage.on('response')event listeners. To trace redirects specifically, you must listen for theresponseevent, as this contains the HTTP status code and the final URL. - Implement the Redirect Logic: Inside the
responselistener, check for status codes in the 3xx range (301, 302, 307, 308). When a 3xx code is detected, log theresponse.url()and theresponse.status(). - Navigate to the Target URL: Use
await page.goto('YOUR_URL_HERE', { waitUntil: 'networkidle0' }). Thenetworkidle0option ensures that the script waits until there are no more than 0 network connections for at least 500ms, capturing the entire chain. - Close the Browser: Once the navigation is complete and the final destination is reached, call
await browser.close()to free up system resources. - Run the Script: Execute your script using
node trace.js. The terminal will output each step of the redirect chain in the order it occurred.
Common Mistakes
- Ignoring the Response Event: Many users try to trace redirects using the
requestevent. However, therequestevent only tells you what was asked for, not how the server responded. You must monitor theresponseevent to see the 3xx status codes. - Incorrect WaitUntil Settings: Using
domcontentloadedmay cause the script to terminate before the final redirect in a long chain has fully resolved. Always usenetworkidle0ornetworkidle2for redirect tracing. - Forgetting Async/Await: Puppeteer operations are asynchronous. Failing to use
awaitwill result in the script attempting to close the browser before the network requests have even been initiated. - Overlooking Meta Refreshes: Some redirects happen via HTML
<meta http-equiv="refresh">tags rather than HTTP headers. These do not trigger 3xx status codes and require monitoring thepage.on('framenavigated')event instead.
Tips
- Capture Headers: Use
response.headers()to extract theLocationheader. This provides the exact destination the server is pointing to before the browser actually makes the next request. - Filter Noise: In a production environment, a single page load can trigger dozens of requests for images and CSS. Filter your logs to only show requests where the URL matches the main domain or the status code is 3xx.
- Use a Custom User Agent: Some servers redirect differently based on the device. Use
page.setUserAgent()to mimic a mobile device or a specific browser version to see if the redirect logic changes. - Log Timestamps: Add
Date.now()to your logs to calculate the latency between each jump in the redirect chain.
Troubleshooting
- Browser Fails to Launch: If you encounter errors regarding missing dependencies (common on Linux), ensure that all Chrome shared libraries are installed. You may need to install packages like
libnss3andlibatk1.0-0. - Redirect Loop (Infinite Loop): If the script hangs or crashes, you may have hit a redirect loop. Implement a counter variable within your response listener; if the number of redirects exceeds a limit (e.g., 20), force the browser to close and log a "Redirect Loop Detected" error.
- Missing Redirects: If some jumps are missing, check if the redirect is happening via JavaScript (
window.location.href). These are not HTTP redirects. To catch these, you must monitorpage.on('request')and look for the sequence of navigation requests. - Timeout Errors: If the page takes too long to resolve, increase the timeout in the
gotooptions by addingtimeout: 60000(60 seconds).
Frequently Asked Questions
Does this method work for 301 and 302 redirects?
Yes, this method captures all HTTP-level redirects, including permanent (301) and temporary (302) redirects, as it monitors the raw HTTP response status codes.
Can I trace redirects without writing code?
While you can use the "Preserve Log" checkbox in standard Chrome DevTools, the headless approach is required for automation, large-scale auditing, or environments where a GUI is unavailable.
Will this detect redirects caused by JavaScript?
Standard HTTP response monitoring will not detect JS-based redirects. To find these, you must monitor the sequence of requests or use the framenavigated event in Puppeteer.
Is Headless Chrome slower than a standard browser?
Generally, headless mode is faster and consumes fewer resources because it does not have to render the actual UI pixels to a screen.
Can I save the redirect chain to a file?
Yes, instead of using console.log(), you can use the Node.js fs (File System) module to append each detected redirect to a .txt or .json file.