IPRout

Next.js IP Geolocation API Example

Use Next.js server route to call IPRout from trusted code, load the API key from the environment, apply a finite timeout, inspect HTTP status before decoding JSON, and handle caller lookup, explicit IP lookup, and usage as separate response contracts.

Last updated August 10, 2026

How do I prepare Next.js for IPRout?

Use Next.js server route from trusted server-side code and load IPROUT_API_KEY from the environment or the platform's secret store. The setup command below identifies the package or runtime capability used by this tutorial. Keep configuration validation near application startup so a missing secret produces a clear deployment error instead of an unauthenticated request during user traffic. Centralize the base URL, timeout, and authentication in one small client rather than repeating them across controllers, jobs, or components.

npm install next react react-dom

How do I look up 8.8.8.8 with Next.js?

The example sends one explicit lookup to GET /ip/8.8.8.8, applies a ten-second tutorial timeout, provides the Bearer key, rejects a non-success status, and parses JSON. Treat it as the focused request core for an application module: add the imports and framework registration expected by your project, preserve the status and safe error body for diagnostics, and return a typed application result rather than exposing the upstream secret or every field directly to a browser.

export async function GET() {
  const response = await fetch("https://api.iprout.com/ip/8.8.8.8", {
    headers: { Authorization: `Bearer ${process.env.IPROUT_API_KEY}` },
    signal: AbortSignal.timeout(10_000),
    cache: "no-store",
  });
  if (!response.ok) return Response.json({ error: "Lookup failed" }, { status: response.status });
  return Response.json(await response.json());
}

How do I switch to caller IP lookup?

Request https://api.iprout.com/ip with no address after /ip and keep the same Next.js server route configuration. Remember that a server-side call identifies the API caller unless your application intentionally resolves a validated end-user address and uses the explicit endpoint. In applications behind a CDN or load balancer, configure proxy trust at your own boundary instead of accepting arbitrary client-supplied forwarding headers. Use caller context as an editable default or supporting signal, not as proof of identity or physical presence.

GET https://api.iprout.com/ip

How do I retrieve account and key usage?

Send the same authentication header to GET https://api.iprout.com/usage. Parse month, total_requests, monthly_limit, remaining_requests, and the api_keys array separately from the IpInfo response. Usage retrieval does not consume lookup allowance, but applications should poll it at a modest interval rather than before every request. Keep this response behind an authenticated server or operations interface because it contains account and key-level capacity information. Compare shared account remaining capacity with each key's remaining value when diagnosing HTTP 429.

GET https://api.iprout.com/usage

How should Next.js model the lookup response?

Use the normal JSON facilities for Next.js and model optional geographic and network values as nullable. The resolved ip, country, country_code, region, city, timezone, utc_offset, latitude, longitude, asn, organization, currency, and calling_code belong to one success object. Do not infer an error from a missing city; inspect the HTTP status first. Ignore additive properties that the application does not use, preserve numbers as numbers, and map the upstream response into a narrower product type when only a country or timezone suggestion is needed.

Field groupExamplesClient behavior
IdentityipRequired resolved address
Locationcountry, region, cityAllow nullable detail
Timetimezone, utc_offsetPrefer IANA timezone
Networkasn, organizationAllow nullable values

How should HTTP errors be handled?

Branch on the status before decoding success data. HTTP 401 means the Next.js process did not provide a valid key. HTTP 422 means the explicit address must be corrected. HTTP 429 means the calling key cap or shared monthly allowance has been reached, so immediate retry is not useful. HTTP 500 and selected transport failures can be retried with a small attempt limit, exponential backoff, and jitter. Redact Authorization and X-API-Key from exceptions, request logging, tracing, and framework debug pages.

StatusMeaningAction
401AuthenticationCheck or rotate key
422Invalid IPCorrect input
429Capacity reachedInspect usage
500Server failureRetry cautiously

How should Next.js timeouts and retries be configured?

Keep a finite request timeout even when Next.js server route supplies a default. Ten seconds is intentionally conservative for a tutorial; measure latency from the actual deployment region and choose a bound that protects the calling request budget. Reuse HTTP connections where the runtime supports it and cancel work when the parent request or job is no longer useful. Do not create nested retry behavior in both a framework client and application wrapper. Optional localization or analytics enrichment should degrade to a neutral result rather than blocking the primary product indefinitely.

How do I test the Next.js integration?

Unit-test the HTTP boundary with fixtures for the documented 8.8.8.8 response, nullable fields, unknown additive fields, usage data, and each error status. Simulate a timeout and an invalid non-JSON intermediary response. Run a small CI integration test only with a designated nonproduction key injected through secrets, and keep live calls out of ordinary unit tests. Verify that 401 and 422 are not retried, 500 retry attempts are bounded, and the application fallback does not fabricate geographic data.

What should be reviewed before deploying Next.js?

Confirm that the live secret is absent from source, browser bundles, generated documentation, screenshots, and logs. Give the service a descriptive key where the plan supports multiple active credentials, apply exact CORS origins only when direct browser access is intentional, and choose a bounded Pro cap where workload isolation matters. Monitor status, latency, shared remaining usage, and per-key consumption. Document ownership, expected volume, fallback, privacy retention, and key rotation so the integration remains understandable after the initial implementation.

External references

Continue with the standards and official documentation most relevant to this guide.

Continue building with IPRout

Test the API, browse runnable examples, or return to the documentation directory.