In this lesson, you will learn how to create a middleware that duplicates incoming production traffic to a staging environment to safely test new features.
What is Request Shadowing?
Request shadowing (or mirroring) allows you to copy live user requests and send them to a secondary environment—like a staging or debug server—without the end-user knowing. This is incredibly powerful because it lets you see how your new code handles real-world traffic patterns, edge cases, and load spikes without risking the production experience.
The key is that the "shadowed" request is fire-and-forget: your production server waits for a response from the actual user, but it sends a copy to the staging server asynchronously, ignoring any result that comes back from the shadow target.
Practical Implementation
In Node.js, you can achieve this by creating a simple middleware that intercepts the req object. You capture the request data, forward it to your secondary URL using a library like axios or node-fetch, and ensure that any errors on the staging side don't crash your main production loop.
const axios = require('axios');
function requestShadowingMiddleware(req, res, next) {
// 1. Capture the payload (if it's a POST/PUT request)
const shadowPayload = req.body;
// 2. Fire and forget to the staging environment
axios.post('https://staging.example.com' + req.originalUrl, shadowPayload)
.catch(err => console.error('Shadowing failed, but production continues: ', err.message));
// 3. Continue the request chain for the production user
next();
}
Important Considerations
When mirroring traffic, you must be careful not to create "side effects" in your staging database. If your shadowed requests perform operations like sending real emails, charging credit cards, or updating public records, you must ensure the staging environment has those external services mocked or disabled.
Additionally, because shadowing adds network overhead to every request, ensure your mirroring logic is non-blocking and uses a timeout to prevent the staging network latency from impacting your production responsiveness.
Key Takeaway: Request shadowing provides a risk-free way to validate how your application handles real production traffic by asynchronously forwarding requests to a secondary environment while keeping the main user experience untouched.