Configuring Rotating Proxies for Next.js SSR Fetching
November 15, 2026
Why Use Rotating Proxies for Server‑Side Fetching
Server‑side rendering (SSR) in Next.js often calls external APIs or scrapes pages during getServerSideProps or in API routes. When many requests originate from the same IP, targets may throttle, block, or serve stale content. Rotating proxies solve this by presenting a fresh exit IP for each request or after a configurable interval, which:
- Distributes traffic across many IPs, reducing the chance of rate‑limit hits.
- Allows geo‑targeted fetches when the proxy pool offers country selection.
- Keeps long‑running scraping jobs alive even if a single IP gets banned.
Prerequisites
- Node.js 18+ (native
fetchandAbortController). - A Next.js project (pages router or app router).
- An active proxy account that provides a gateway host, HTTP port, username, and password. If you are using RoProxy, the gateway host and credentials are provided in your dashboard.
- An API key for on‑demand rotation (available on Pro and Business plans).
Store the connection details in environment variables so they never appear in source control:
# .env.local
PROXY_HOST=GATEWAY_HOST
PROXY_PORT=HTTP_PORT
PROXY_USER=USERNAME
PROXY_PASS=PASSWORD
PROXY_API_KEY=API_KEY
Configuring the Proxy in Next.js
Create a small utility that builds an https-proxy-agent instance. The agent works for both HTTP and HTTPS targets because the gateway accepts CONNECT tunnelling on the same port.
// lib/proxy-agent.js
import { HttpsProxyAgent } from 'https-proxy-agent';
const host = process.env.PROXY_HOST;
const port = process.env.PROXY_PORT;
const user = process.env.PROXY_USER;
const pass = process.env.PROXY_PASS;
if (!host || !port || !user || !pass) {
throw new Error('Proxy environment variables are not set');
}
// http://USERNAME:PASSWORD@GATEWAY_HOST:HTTP_PORT
const proxyUrl = `http://${user}:${pass}@${host}:${port}`;
export function getProxyAgent() {
return new HttpsProxyAgent(proxyUrl);
}
Using the Agent in getServerSideProps
// pages/products/[id].js
export async function getServerSideProps({ params }) {
const agent = getProxyAgent();
const res = await fetch(`https://api.example.com/products/${params.id}`, {
agent, // Node 18+ supports the `agent` option
headers: { 'Accept': 'application/json' },
// optional: abort after 10 s
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) {
return { notFound: true };
}
const data = await res.json();
return { props: { product: data } };
}
Using the Agent in an API Route
// pages/api/external.js
export default async function handler(req, res) {
const agent = getProxyAgent();
try {
const upstream = await fetch('https://httpbin.org/ip', { agent });
const json = await upstream.json();
res.status(200).json(json);
} catch (err) {
console.error('Proxy request failed:', err);
res.status(502).json({ error: 'Bad gateway' });
}
}
Both examples send the request through the rotating proxy without any code changes in the business logic.
Rotating the IP on Demand
The proxy pool offers two rotation modes:
- Sticky – the IP stays the same until you explicitly rotate or the IP fails.
- Timed – the IP changes automatically after a customer‑defined interval.
On Pro and Business plans you can force an immediate rotation via the session API. The call requires the session identifier (SESSION_ID) and your API key.
// lib/rotate-proxy.js
export async function rotateProxy(sessionId) {
const apiKey = process.env.PROXY_API_KEY;
if (!apiKey) throw new Error('PROXY_API_KEY not set');
const resp = await fetch(
`https://backend-api.ro-proxy.com/api/session/${sessionId}/rotate`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
}
);
if (!resp.ok) {
const txt = await resp.text();
throw new Error(`Rotation failed: ${resp.status} ${txt}`);
}
return resp.json(); // contains new IP info
}
You can call rotateProxy after a batch of requests, when you detect a 429/403 response, or on a schedule using setInterval in a long‑running worker.
Handling Errors and Retries
Proxy connections can fail for several reasons:
- 407 Proxy Authentication Required – credentials are wrong or expired.
- 401 Unauthorized – API key invalid for rotation endpoint.
- Network errors – gateway unreachable, DNS issues, TLS handshake failure.
A small retry wrapper with exponential back‑off keeps the scraper resilient:
// lib/fetch-with-retry.js
export async function fetchWithRetry(url, options = {}, retries = 3, baseDelay = 500) {
for (let attempt = 0; ; attempt++) {
try {
return await fetch(url, options);
} catch (err) {
if (attempt >= retries) throw err;
const delay = baseDelay * 2 ** attempt + Math.random() * 100;
await new Promise(r => setTimeout(r, delay));
}
}
}
Use it like:
const agent = getProxyAgent();
const res = await fetchWithRetry('https://api.example.com/data', { agent });
Testing the Setup
Verify that traffic really exits through the proxy by calling an IP‑echo service. Add a temporary API route:
// pages/api/test-proxy.js
export default async function handler(req, res) {
const agent = getProxyAgent();
try {
const r = await fetch('https://api.ipify.org?format=json', { agent });
const data = await r.json();
res.status(200).json(data); // { "ip": "<exit‑ip>" }
} catch (e) {
res.status(500).json({ error: e.message });
}
}
Visit /api/test-proxy in the browser or with curl. The returned IP should differ from your server’s public IP and change when you invoke rotateProxy.
Conclusion
Routing Next.js server‑side fetches through a rotating proxy is a few lines of configuration: build an HttpsProxyAgent from your gateway credentials, pass it to fetch, and optionally call the rotation endpoint when you need a fresh IP. This pattern keeps SSR data fresh, avoids blocks, and works the same way in API routes, getServerSideProps, or custom Node scripts. With RoProxy you can manage the rotation mode and trigger instant IP changes programmatically, giving you full control over the exit identity of every server‑side request.