The official Next.js proxy middleware for the InternetData API.
It looks up the visitor behind each request, where they are, which network they come from and whether it's a VPN, a proxy, Tor or a hosting server, and forwards the answer to your app, where Server Components and Route Handlers can read it. Blocking is opt-in.
npm install internetdata-nextRequires Node.js 22 or newer and Next.js 15 or newer. The proxy runs on the Node.js runtime and, on Next 15, on the Edge runtime too.
Without an API key a lookup answers the basics: the country and the network behind the address, Tor, relay and anycast. The address's company and its abuse contact come with a free key's full answers or a paid plan, so the basics leave them out. Every lookup your app makes comes from your server's address, though, and a source address's lookups without a key are limited each UTC day, so a busy site will see them refused; a free key answers past that. A paid plan answers every field, VPN, the proxy flags, hosting, CDN, bots, carriers, satellites, the service flags, the company and the city among them; create a key in the console. A free key answers every field on its organization's first lookups each UTC day, then each lookup fails as quota_exceeded (below).
Next 16 renamed the file convention from middleware.ts to proxy.ts, and the export from middleware to proxy. Both work on 16, where middleware.ts logs a deprecation, so use whichever your version supports.
// proxy.ts
import { createProxy } from 'internetdata-next';
export const proxy = createProxy({ apiKey: process.env.INTERNETDATA_API_KEY });
export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] };On Next 15 the file is middleware.ts, and it runs on the Edge runtime unless its config asks for runtime: 'nodejs', which is stable from 15.5. Either works:
// middleware.ts, on Next 15
import { createProxy } from 'internetdata-next';
export const middleware = createProxy({ apiKey: process.env.INTERNETDATA_API_KEY });
export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] };Then read the answer anywhere downstream:
// app/page.tsx
import { Suspense } from 'react';
import { headers } from 'next/headers';
import { readLookup } from 'internetdata-next';
async function Greeting() {
const lookup = readLookup(await headers());
return `Hello, visitor from ${lookup?.result?.location.country_name ?? 'somewhere'}`;
}
export default function Page() {
return (
<main>
<Suspense fallback="Hello">
<Greeting />
</Suspense>
</main>
);
}The read of headers() sits inside <Suspense> because a new Next 16 app turns Cache Components on, and next build then refuses a page that reads request data outside one.
By default nothing is blocked. Your own code decides what the answer means: a currency to show, a sign-up to review, a page to keep from some countries.
Set a matcher. Without one the proxy runs on every request including static assets, which costs a lookup each.
Pass a blockCondition and a matching request is answered with 403 and never reaches your app.
export const proxy = createProxy({
apiKey: process.env.INTERNETDATA_API_KEY,
blockCondition: { location: { country: ['CU', 'IR', 'KP'] } },
});A condition is written in the shape of a result, and only the members you name are considered, so it can refuse on anything in the answer. The country works on every plan, and so do isTor, isRelay and isAnycast; the others here need a paid plan or a free key's full answers:
blockCondition: { asn: { type: 'hosting' } } // the network's type
blockCondition: [{ isAnycast: true }, { isSatellite: true }] // anycast and satellite space
blockCondition: { isBot: true } // crawlers, monitors and scanners
blockCondition: [{ isHosting: true }, { isCdn: true }] // traffic from servers, not people
blockCondition: [{ isVpn: true }, { isTor: true }, { isResproxy: true }] // anonymity: a list is OR
blockCondition: { isVpn: true, vpn: { provider: 'nordvpn' } } // one provider
blockCondition: { resproxy: { hits: { gte: 5 } } } // a numeric thresholdValues are matched by equality, strings without regard to case. An array means any-of. { gte, gt, lte, lt } compares numbers, and every bound you give must hold, so two of them are a range. A member the answer holds as a list matches when any one element does, every member of an object term on the same element: { web: { port: 443 } }, { pubproxy: { protocols: 'socks5' } }. Members you set to false or null are ignored, so a condition states the signals you act on; one that constrains nothing would match every request, and is refused when the proxy is created rather than silently blocking all your traffic.
Replace the refusal with onBlocked. A redirect is usually friendlier than a 403:
onBlocked: (request) => NextResponse.redirect(new URL('/unavailable', request.url)),allowBots sends a request's own User-Agent with its lookup when it names a crawler, and a request whose answer's userAgent.verdict is verified, a crawler its operator vouches for such as Googlebot from Google's addresses, is never blocked, whatever blockCondition matches. The answer is still forwarded, its user_agent included:
export const proxy = createProxy({
apiKey: process.env.INTERNETDATA_API_KEY,
blockCondition: { isBot: true },
allowBots: true,
});A client claiming to be a crawler from an address its operator does not vouch for reads spoofed, so blockCondition: { userAgent: { verdict: 'spoofed' } } refuses a forged crawler. Any other agent, or none, is not sent, since its verdict could only be not_bot. One address is looked up with at most four crawler agents an hour: past those its lookup sends none, and a request passes as a crawler only where the answer's bot.verified is true. It is off by default, and then no agent is sent and the cache keeps one answer per address rather than one per address and agent. A verdict needs a paid plan or a free key's full answers: a served answer without one is reported once under onMissingField.
Most apps already have a proxy. Use createGuard and call it from yours:
import { NextResponse } from 'next/server';
import { createGuard } from 'internetdata-next';
const guard = createGuard({ apiKey: process.env.INTERNETDATA_API_KEY });
export async function proxy(request: NextRequest) {
const lookup = await guard(request);
if (lookup?.result?.isTor) {
return NextResponse.redirect(new URL('/verify', request.url));
}
return guard.forward(request, lookup);
}guard.forward continues to your app carrying the answer. Return it rather than a bare NextResponse.next(), or nothing downstream can read the lookup.
This is the setting that decides whether any of the above works, and Next makes it more your problem than most frameworks do.
Next has no socket peer to offer. NextRequest.ip was removed in Next 15, and a proxy runs ahead of the server, so a forwarded header is the only address available: this is the one place where the default is a header rather than a connection.
The default reads the left-most X-Forwarded-For entry. That is correct when the platform in front of you overwrites the header, which Vercel does and any ingress you control can be configured to. Behind something that appends, the left-most entry is whatever the visitor sent, so they choose the address that gets looked up.
For a platform that writes its own header, name it:
import { headerIpSelector } from 'internetdata-next';
createProxy({
apiKey: process.env.INTERNETDATA_API_KEY,
ipSelector: headerIpSelector('CF-Connecting-IP'), // or True-Client-IP, or your own
});If you know how many proxies sit in front, count from the right: xffIpSelector({ depth: 1 }) is the address your nearest proxy saw. Anything else, pass your own function. It receives the NextRequest and returns an address.
If the address resolves to a private one, or to nothing at all, the proxy says so once on console.warn. That is expected running locally and is the signal to fix your configuration anywhere else.
The answer travels to your app on x-internetdata, because a proxy runs in its own context and a request header is the only thing that crosses into it.
Any copy the caller sent is deleted before ours is written. That overwrite is the entire basis of trusting it downstream: without it a visitor could set the header themselves and tell your app whatever they liked about their own address. It is the same rule an ingress follows for a real-IP header, and it holds even when the request was skipped.
Turn it off with forward: false if you only ever block and never read the answer.
The request is let through, and the reason is on lookup.error. Our outage should not become yours, so a network failure, a rate limit or a rejected key all fail open. Pass failClosed: true to block instead.
A key whose organization has used up its lookups with every field (a free key's full answers for the UTC day, a paid key's quota or overage cap) is answered with the basics, and the client library raises quota_exceeded for that answer, so the proxy treats it as a failed lookup too: the request goes through with no result and error quota_exceeded, an error-level log naming quota_exceeded goes to console.error (or the onError you pass) once a minute at most, and failClosed: true refuses it. A guard's lookup.error.result has the basics if you want them:
const lookup = await guard(request);
if (lookup?.error?.kind === 'quota_exceeded') {
// the organization's lookups with every field are used up
const basics = lookup.error.result;
}
return guard.forward(request, lookup);Answers are cached for an hour per proxy instance, so a returning visitor costs nothing, and private addresses never leave the process. A cache miss is one request to our API, bounded at 2500 ms by default and not retried: on a request path, failing open quickly beats holding a visitor while we try again.
createProxy({ apiKey: KEY, timeoutMs: 1000, retries: 1, cache: { max: 50000, ttlMs: 600000 } })A serverless deployment gets less from the cache than a long-running one, because the instance holding it is short-lived. Narrow the matcher, or skip what you do not care about:
skip: (request) => request.nextUrl.pathname.startsWith('/api/health'),Beyond a few million distinct visitors a day, stop calling the API per request: look addresses up locally in our databases instead.
The basics, what a lookup answers without a key, leave out isVpn, isHosting, isCdn, the four proxy flags, isBot, isCarrier, isSatellite and the five service flags, the detail behind them, user_agent, company and abuse, and the paid members inside location and asn, such as location.city; a free key's answers past its organization's full answers for the UTC day are the basics too, and fail the lookup as quota_exceeded. A field the answer leaves out is absent, which means "not in this answer" rather than "checked, and no", company, abuse and the flags included. The forwarded answer keeps its wire names, so it carries a member only when the API sent it:
lookup.result?.is_vpn ?? false // when you only want the flagA blockCondition naming a member your plan does not serve, location.city or a member of company included, can never match, so the proxy warns once instead of failing silently. Set onMissingField: 'throw' to make it an error.
There are official InternetData client libraries available for many languages including PHP, Python, Go, Java, and Ruby. See our GitHub at https://github.com/internetdata for more.
Geolocation, anonymity, ownership, network, service and domain data for any IP address, AS or domain, by API or as databases you download.
This project is licensed under the MIT License.