[{"data":1,"prerenderedAt":35},["ShallowReactive",2],{"blog:post:en:configuring-rotating-proxies-nextjs-ssr-fetching":3,"blog:related:en:configuring-rotating-proxies-nextjs-ssr-fetching":22},{"slug":4,"lang":5,"title":6,"summary":7,"date":8,"tags":9,"tag_slugs":14,"thumbnail_url":15,"translations":16,"body":17,"asset_base":18,"checksum":19,"published_at":20,"content_updated_at":21},"configuring-rotating-proxies-nextjs-ssr-fetching","en","Configuring Rotating Proxies for Next.js SSR Fetching","Learn how to route Next.js server‑side data fetching through rotating proxies, handle authentication, and rotate IPs on demand using the RoProxy API.","2026-11-15",[10,11,12,13],"proxy","proxy-configuration","proxy-rotation","nodejs",[10,11,12,13],"https://blog-api.ro-proxy.com/api/blog/posts/configuring-rotating-proxies-nextjs-ssr-fetching/thumbnail.svg?lang=en",[5],"## Why Use Rotating Proxies for Server‑Side Fetching\n\nServer‑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:\n\n* Distributes traffic across many IPs, reducing the chance of rate‑limit hits.\n* Allows geo‑targeted fetches when the proxy pool offers country selection.\n* Keeps long‑running scraping jobs alive even if a single IP gets banned.\n\n## Prerequisites\n\n* Node.js 18+ (native `fetch` and `AbortController`).\n* A Next.js project (pages router or app router).\n* 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.\n* An API key for on‑demand rotation (available on Pro and Business plans).\n\nStore the connection details in environment variables so they never appear in source control:\n\n```bash\n# .env.local\nPROXY_HOST=GATEWAY_HOST\nPROXY_PORT=HTTP_PORT\nPROXY_USER=USERNAME\nPROXY_PASS=PASSWORD\nPROXY_API_KEY=API_KEY\n```\n\n## Configuring the Proxy in Next.js\n\nCreate 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.\n\n```js\n// lib/proxy-agent.js\nimport { HttpsProxyAgent } from 'https-proxy-agent';\n\nconst host = process.env.PROXY_HOST;\nconst port = process.env.PROXY_PORT;\nconst user = process.env.PROXY_USER;\nconst pass = process.env.PROXY_PASS;\n\nif (!host || !port || !user || !pass) {\n  throw new Error('Proxy environment variables are not set');\n}\n\n// http://USERNAME:PASSWORD@GATEWAY_HOST:HTTP_PORT\nconst proxyUrl = `http://${user}:${pass}@${host}:${port}`;\n\nexport function getProxyAgent() {\n  return new HttpsProxyAgent(proxyUrl);\n}\n```\n\n### Using the Agent in `getServerSideProps`\n\n```js\n// pages/products/[id].js\nexport async function getServerSideProps({ params }) {\n  const agent = getProxyAgent();\n  const res = await fetch(`https://api.example.com/products/${params.id}`, {\n    agent,               // Node 18+ supports the `agent` option\n    headers: { 'Accept': 'application/json' },\n    // optional: abort after 10 s\n    signal: AbortSignal.timeout(10_000),\n  });\n\n  if (!res.ok) {\n    return { notFound: true };\n  }\n\n  const data = await res.json();\n  return { props: { product: data } };\n}\n```\n\n### Using the Agent in an API Route\n\n```js\n// pages/api/external.js\nexport default async function handler(req, res) {\n  const agent = getProxyAgent();\n  try {\n    const upstream = await fetch('https://httpbin.org/ip', { agent });\n    const json = await upstream.json();\n    res.status(200).json(json);\n  } catch (err) {\n    console.error('Proxy request failed:', err);\n    res.status(502).json({ error: 'Bad gateway' });\n  }\n}\n```\n\nBoth examples send the request through the rotating proxy without any code changes in the business logic.\n\n## Rotating the IP on Demand\n\nThe proxy pool offers two rotation modes:\n\n* **Sticky** – the IP stays the same until you explicitly rotate or the IP fails.\n* **Timed** – the IP changes automatically after a customer‑defined interval.\n\nOn 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.\n\n```js\n// lib/rotate-proxy.js\nexport async function rotateProxy(sessionId) {\n  const apiKey = process.env.PROXY_API_KEY;\n  if (!apiKey) throw new Error('PROXY_API_KEY not set');\n\n  const resp = await fetch(\n    `https://backend-api.ro-proxy.com/api/session/${sessionId}/rotate`,\n    {\n      method: 'POST',\n      headers: {\n        'Authorization': `Bearer ${apiKey}`,\n        'Content-Type': 'application/json',\n      },\n    }\n  );\n\n  if (!resp.ok) {\n    const txt = await resp.text();\n    throw new Error(`Rotation failed: ${resp.status} ${txt}`);\n  }\n  return resp.json(); // contains new IP info\n}\n```\n\nYou 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.\n\n## Handling Errors and Retries\n\nProxy connections can fail for several reasons:\n\n* **407 Proxy Authentication Required** – credentials are wrong or expired.\n* **401 Unauthorized** – API key invalid for rotation endpoint.\n* **Network errors** – gateway unreachable, DNS issues, TLS handshake failure.\n\nA small retry wrapper with exponential back‑off keeps the scraper resilient:\n\n```js\n// lib/fetch-with-retry.js\nexport async function fetchWithRetry(url, options = {}, retries = 3, baseDelay = 500) {\n  for (let attempt = 0; ; attempt++) {\n    try {\n      return await fetch(url, options);\n    } catch (err) {\n      if (attempt >= retries) throw err;\n      const delay = baseDelay * 2 ** attempt + Math.random() * 100;\n      await new Promise(r => setTimeout(r, delay));\n    }\n  }\n}\n```\n\nUse it like:\n\n```js\nconst agent = getProxyAgent();\nconst res = await fetchWithRetry('https://api.example.com/data', { agent });\n```\n\n## Testing the Setup\n\nVerify that traffic really exits through the proxy by calling an IP‑echo service. Add a temporary API route:\n\n```js\n// pages/api/test-proxy.js\nexport default async function handler(req, res) {\n  const agent = getProxyAgent();\n  try {\n    const r = await fetch('https://api.ipify.org?format=json', { agent });\n    const data = await r.json();\n    res.status(200).json(data); // { \"ip\": \"\u003Cexit‑ip>\" }\n  } catch (e) {\n    res.status(500).json({ error: e.message });\n  }\n}\n```\n\nVisit `/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`.\n\n## Conclusion\n\nRouting 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.\n","https://blog-api.ro-proxy.com/api/blog/posts/configuring-rotating-proxies-nextjs-ssr-fetching/assets","205a330d00403a33d5d11bbebb62dd34509f700bca5c41675cc7fdd3b38ce526","2026-11-15T01:07:11.35726Z","2026-11-15T01:07:11.359668Z",[23,27,31],{"slug":24,"title":25,"summary":26},"keep-proxy-credentials-out-of-logs-and-urls","Keep Proxy Credentials Out of Logs and URLs","Proxy credentials leak through URLs, debug logs, and shell history. Learn concrete patterns to keep them out of Python, Node.js, cURL, and CI.",{"slug":28,"title":29,"summary":30},"scheduled-proxy-ip-rotation-python","Schedule Proxy IP Rotation in Python","Use timed proxy rotation for predictable Python scrapers, with requests code, retry checks, and safe IP change scheduling.",{"slug":32,"title":33,"summary":34},"proxy-retry-budgets-nodejs-fetch","Proxy Retry Budgets for Node.js Fetch","Set retry budgets and backoff for Node.js fetch calls through rotating proxies to survive timeouts, 429, and 503 errors.",1794816128075]