The IP API The IP API
// Guide

Country-Based Redirects in Next.js and Express

Nov 23rd, 2026 // 7 min read
Country-Based Redirects in Next.js and Express

If you searched for how to do a Next.js redirect by country, the short answer is: resolve the visitor's IP to a country code with a geolocation API inside middleware, then rewrite or redirect based on the result - with a few guardrails so you do not break crawlers or annoy travelers. This guide gives you a complete recipe for both Next.js and Express, using The IP API's GET /v1/ip/{ip} endpoint, plus the UX rules that separate a helpful localization flow from a hostile one.

The response field we care about is body.location.country_code, an ISO 3166-1 alpha-2 code like US or DE. The full response shape is in the documentation.

The ground rules before any code

Three decisions apply to both frameworks, so settle them first.

Read the client IP correctly. Your app almost certainly sits behind a proxy or load balancer, so the TCP peer address is the proxy, not the visitor. The real client IP arrives in the X-Forwarded-For header, which is a comma-separated chain where the left-most entry is the original client - and where anything not appended by infrastructure you control can be spoofed. In Express, set trust proxy to match your topology instead of parsing the header yourself. During local development you will see 127.0.0.1 or ::1; The IP API returns those as bogons (is_bogon: true with no location data), so your code must tolerate a missing location.

Cache lookups per IP. The country an IP maps to changes rarely, and repeat visitors hit your middleware on every request. A tiny in-memory Map with a TTL eliminates nearly all duplicate lookups. You do not need the batch endpoint for this pattern - requests arrive one visitor at a time, and the cache absorbs the volume.

Fail open. If the lookup errors or times out, serve the default locale. Geolocation should never take your site down.

Express: a country middleware with an in-memory cache

This example requires Node 18+ (for global fetch) and npm install express cookie-parser.

const express = require("express");
const cookieParser = require("cookie-parser");

const app = express();
app.set("trust proxy", 1); // one proxy hop (nginx, ALB, etc.)
app.use(cookieParser());

const API_KEY = process.env.THEIPAPI_KEY;
const TTL_MS = 24 * 60 * 60 * 1000; // 24h; country data rarely changes
const cache = new Map(); // ip -> { country, expires }
const REGIONS = new Set(["en", "de"]); // every valid region path prefix

async function countryForIp(ip) {
  const hit = cache.get(ip);
  if (hit && hit.expires > Date.now()) return hit.country;

  const res = await fetch(
    `https://api.theipapi.com/v1/ip/${ip}?api_key=${API_KEY}`
  );
  if (!res.ok) return null;

  const data = await res.json();
  // Bogons (localhost, private ranges) have no location block,
  // and a miss can be HTTP 200 with status "Error".
  if (data.status !== "OK" || !data.body.location) return null;

  const country = data.body.location.country_code;
  cache.set(ip, { country, expires: Date.now() + TTL_MS });
  return country;
}

app.use(async (req, res, next) => {
  try {
    res.locals.country = await countryForIp(req.ip);
  } catch {
    res.locals.country = null; // fail open
  }
  next();
});

// Redirect only on the entry route, and only without an explicit choice.
app.get("/", (req, res) => {
  if (REGIONS.has(req.cookies.region)) {
    return res.redirect(302, `/${req.cookies.region}/`);
  }
  if (res.locals.country === "DE") {
    return res.redirect(302, "/de/");
  }
  res.redirect(302, "/en/");
});

// The manual switcher wins over geolocation, permanently.
app.get("/set-region/:region", (req, res) => {
  if (!REGIONS.has(req.params.region)) {
    return res.status(404).send("Unknown region");
  }
  res.cookie("region", req.params.region, {
    maxAge: 365 * 24 * 60 * 60 * 1000,
    httpOnly: true,
  });
  res.redirect(302, `/${req.params.region}/`);
});

app.listen(3000);

Points worth noticing:

  • With trust proxy set, Express derives req.ip from X-Forwarded-For by walking from the right and skipping the proxy hops you declared trusted - so a spoofed entry a client prepends to the header is ignored. No manual header parsing.
  • The middleware only annotates res.locals.country; the redirect decision lives in one route. That keeps /en/ and /de/ freely reachable, which matters for crawlers (more below).
  • The cookie check comes before the geolocation check. Once a visitor picks a region, their IP no longer matters.
  • Every redirect target is validated against the REGIONS allowlist. Echoing an unvalidated path segment or cookie value into a redirect is an open-redirect vulnerability - a crafted value like //evil.example becomes a protocol-relative URL, and your /set-region endpoint turns into a phishing hop.
  • The naive Map grows unboundedly under a flood of unique IPs. For production, swap in an LRU (lru-cache is the standard choice) with the same get/set shape.

Next.js redirect by country with middleware.ts

In Next.js, geolocation belongs in middleware.ts, which runs before a request is matched to a page. Edge middleware has fetch available, and server-side environment variables like THEIPAPI_KEY are readable there - set the variable in your hosting environment, and do not prefix it NEXT_PUBLIC_, which would leak your key to the browser.

// middleware.ts (project root)
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

// Only run on the routes that should localize.
export const config = {
  matcher: ["/", "/pricing"],
};

const LOCALES: Record<string, string> = {
  DE: "de",
  FR: "fr",
};
const VALID_LOCALES = new Set(Object.values(LOCALES));

export async function middleware(request: NextRequest) {
  // 1. An explicit user choice always wins over IP geolocation.
  const chosen = request.cookies.get("region")?.value;
  if (chosen && VALID_LOCALES.has(chosen)) {
    return NextResponse.rewrite(
      new URL(`/${chosen}${request.nextUrl.pathname}`, request.url)
    );
  }

  // 2. Left-most X-Forwarded-For entry; on Vercel and most hosts
  // this is the real client IP.
  const ip = request.headers.get("x-forwarded-for")?.split(",")[0].trim();
  if (!ip) return NextResponse.next();

  try {
    const res = await fetch(
      `https://api.theipapi.com/v1/ip/${ip}?api_key=${process.env.THEIPAPI_KEY}`
    );
    if (!res.ok) return NextResponse.next();

    const data = await res.json();
    if (data.status !== "OK" || !data.body?.location) {
      return NextResponse.next();
    }

    const locale = LOCALES[data.body.location.country_code];
    if (locale) {
      return NextResponse.rewrite(
        new URL(`/${locale}${request.nextUrl.pathname}`, request.url)
      );
    }
  } catch {
    // fail open
  }
  return NextResponse.next();
}

Notes specific to Next.js:

  • Rewrite vs redirect. NextResponse.rewrite serves the localized content at the original URL; NextResponse.redirect sends the browser to the localized URL. Rewrites feel smoother but hide the locale from the address bar; redirects are more transparent and give each locale a canonical URL. For SEO-relevant pages, prefer redirects (or a banner - see below) so each locale has its own indexable address.
  • Caching at the edge. Edge middleware instances are ephemeral, so an in-memory Map is best-effort per instance. A module-scope map still helps for hot paths, but the simplest durable option is to set the resolved country in a cookie on first lookup and short-circuit on that cookie for subsequent requests - one API call per visitor instead of per request.
  • Keep the matcher tight. Middleware runs on every matched request, including prefetches. Matching only the routes that actually localize keeps latency and API usage down.

You can sanity-check what the API returns for your own connection with the free What is my IP tool - the same data your middleware will see.

UX cautions: where country redirects go wrong

Always provide a manual country switcher. IP geolocation is a good default guess, not an identity. A German speaker on holiday in Spain, a VPN user, an office whose egress sits in another country - all of them will be guessed "wrong". A visible switcher (and the cookie logic above) turns a wrong guess into a one-click fix instead of a trap. Respecting the cookie before the IP is the single most important line in both recipes.

Do not blanket-redirect crawlers. Googlebot crawls predominantly from US IP addresses. If your site force-redirects every US visitor to /en/, Googlebot may never fetch /de/ or /fr/, and your other locales can drop out of the index. Safer patterns, in rough order of preference:

  1. Keep every locale directly reachable at its own URL, link them with hreflang alternates, and use geolocation only on the bare entry route (/) as in the Express example.
  2. Show a non-blocking suggestion banner ("It looks like you're in Germany - switch to the German site?") instead of redirecting at all. This is the least SEO-risky option and often the best UX too.
  3. If you must redirect broadly, exempt known crawlers - but verify them properly (reverse-then-forward DNS), since user-agent strings are trivially faked.

Redirect on specific routes, not everywhere. Checkout, pricing, and the landing page are where country actually changes what you show - currency, catalog, shipping, licensing. Blog posts and docs rarely need it. This is also why both recipes scope the redirect to specific routes rather than applying it globally.

The same middleware, minus the redirect, is useful well beyond localization: setting res.locals.country and reading it in your handlers powers currency selection, tax hints, and regional catalogs. We cover those patterns in geolocation in e-commerce, and the e-commerce and streaming use-case pages show where country detection fits into licensing and content availability decisions.

Ship it

The whole feature is one middleware function, one cache, and one cookie. Sign up for a free API key to try either recipe - the free tier includes 1,000 requests per day with no card required, which comfortably covers development and a small production site with per-visitor caching in place.

Ivan
About the author
Ivan, Founder, The IP API.
// READY_WHEN_YOU_ARE

Ready to start using The IP API?

Unlock accurate, reliable IP geolocation. Integrate in minutes to enhance personalization, performance, and security.