Express (Node.js)
Express ist das Rückgrat des Node.js-Ökosystems. Um Ihre API-Routen oder Ihre Webanwendung zu schützen, können Sie ProxyTracer als globale oder routenspezifische Middleware implementieren.
Die Middleware
Diese Implementierung extrahiert die Client-IP (behandelt X-Forwarded-For-Header, wenn Sie sich hinter einem Reverse-Proxy wie NGINX oder AWS ALB befinden), fragt ProxyTracer über das native fetch ab und trennt die Verbindung sofort mit einem 403 Forbidden, wenn eine Bedrohung erkannt wird.
const express = require('express');
const app = express();
// Trust the reverse proxy to ensure req.ip is accurate
app.set('trust proxy', true);
const proxyTracerMiddleware = async (req, res, next) => {
// 1. Extract the IP
// Express handles 'trust proxy' automatically, but we can fallback just in case
const ip = req.headers['x-forwarded-for']?.split(',')[0].trim() || req.ip;
// Pass through if local development
if (!ip || ip === '::1' || ip === '127.0.0.1') {
return next();
}
try {
// 2. Query ProxyTracer API (Node 18+ supports native fetch)
const ptResponse = await fetch(`https://api.proxytracer.com/v1/check/${ip}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${process.env.PROXYTRACER_API_KEY}`
}
});
if (ptResponse.ok) {
const data = await ptResponse.json();
// 3. Drop the connection if a proxy/VPN is detected
if (data.proxy === true) {
return res.status(403).json({
error: "Access Denied: VPN or Proxy detected."
});
}
}
} catch (error) {
// Fail open: If the API is unreachable, allow traffic to ensure uptime
console.error('ProxyTracer API Error:', error);
}
// 4. Traffic is clean, proceed to the controller
next();
};
// Apply globally to all routes
app.use(proxyTracerMiddleware);
// Or apply strictly to sensitive routes
// app.post('/api/checkout', proxyTracerMiddleware, checkoutController);Last updated on