npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

next-geo-guard

v1.0.0

Published

Protect Next.js apps from traffic originating outside allowed countries. Multi-source geo verification (Vercel headers, ISP lookup, optional auth metadata).

Downloads

105

Readme

next-geo-guard

Protect your Next.js app from traffic originating outside allowed countries. Uses multi-source geolocation verification (2-of-3) to reduce false positives from VPNs and bad IP data.

Features

  • Multi-source verification: Vercel headers + ISP lookup + optional user metadata (e.g. Clerk)
  • Configurable: Allow multiple countries (US, CA, etc.), customize required passes
  • No lock-in: Works with or without auth; user metadata is optional
  • ISP providers: ip-api.com (free) or ipinfo.io (with token for higher limits)
  • Edge-ready: Runs in Next.js middleware

Install

npm install next-geo-guard

Quick Start

1. Add to your middleware

// middleware.ts
import { clerkClient, clerkMiddleware } from '@clerk/nextjs/server';
import { createGeoGuard } from 'next-geo-guard';

const geoGuard = createGeoGuard({
  allowedCountries: ['US'],
  blockedPath: '/blocked',
  bypassPaths: ['/api/geo/debug', '/sign-in', '/sign-up', '/'],
});

export default clerkMiddleware(async (auth, req) => {
  const geoResponse = await geoGuard(req, async () => {
    const { userId } = await auth();
    if (!userId) return null;
    const user = await clerkClient().users.getUser(userId);
    return { ...user.publicMetadata, ...user.privateMetadata } as Record<string, unknown>;
  });
  if (geoResponse) return geoResponse;
  // ... rest of your middleware
});

2. Without auth (Vercel + ISP only)

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { createGeoGuard } from 'next-geo-guard';

const geoGuard = createGeoGuard({
  allowedCountries: ['US', 'CA'],
  blockedPath: '/blocked',
});

export async function middleware(req: NextRequest) {
  const geoResponse = await geoGuard(req);
  if (geoResponse) return geoResponse;
  return NextResponse.next();
}

3. Create a blocked page

Add /blocked (or your blockedPath) to show when users are restricted. Query params include country, passes, total, reason.

Configuration

| Option | Default | Description | |--------|---------|-------------| | allowedCountries | ['US'] | Country codes that pass verification | | requiredPasses | 2 | When 2+ sources available, require this many to pass | | blockedPath | '/blocked' | Path to rewrite/redirect to when blocked | | bypassPaths | [] | Paths that skip geo check (e.g. sign-in, debug) | | useRewrite | true | Use NextResponse.rewrite vs redirect | | verifiedMaxAgeMs | 24h | How long to trust user metadata before re-verifying | | userMetadataKeys | { country: 'verifiedCountry', verifiedAt: 'verifiedCountryAt' } | Keys to read from user metadata |

Environment Variables

| Variable | Description | |----------|-------------| | IPINFO_ACCESS_TOKEN | Optional. Use ipinfo.io instead of ip-api.com (higher limits, HTTPS) | | GEO_XFF_USE_LAST | Set to 'true' to use last IP from x-forwarded-for (for some proxy setups) | | GEO_GUARD_ALWAYS_RUN | Set to 'true' to run geo checks in development | | NODE_ENV | In production, geo checks run. In development, they are skipped unless GEO_GUARD_ALWAYS_RUN=true |

API Routes (Optional)

Debug endpoint

Help users diagnose VPN/geo issues:

// app/api/geo/debug/route.ts
import { NextResponse } from 'next/server';
import { getClientIp } from 'next-geo-guard';

export const dynamic = 'force-dynamic';
export const runtime = 'edge';

export async function GET(request: Request) {
  const headers = request.headers;
  const clientIp = getClientIp(headers);
  const geoHeaders: Record<string, string> = {};
  for (const key of ['x-vercel-ip-country', 'x-vercel-forwarded-for', 'x-forwarded-for']) {
    const val = headers.get(key);
    if (val) geoHeaders[key] = val;
  }
  return NextResponse.json({ clientIp: clientIp ?? 'NOT FOUND', geoHeaders });
}

Status endpoint

// app/api/geo/status/route.ts
import { NextResponse } from 'next/server';
import { verifyGeoAccess } from 'next-geo-guard';

export async function GET(request: Request) {
  const user = null; // or get from your auth (Clerk, etc)
  const geoResult = await verifyGeoAccess(request.headers, user);
  return NextResponse.json({
    allowed: geoResult.allowed,
    passes: geoResult.passes,
    total: geoResult.total,
    details: geoResult.details,
  });
}

Clerk integration

The package expects user metadata with verifiedCountry and verifiedCountryAt (configurable via userMetadataKeys). When a user passes verification, store:

await clerkClient().users.updateUserMetadata(userId, {
  publicMetadata: {
    verifiedCountry: 'US',
    verifiedCountryAt: Date.now(),
  },
});

The package trusts this for 24h (verifiedMaxAgeMs), then requires re-verification.

How it works

  1. Vercel – reads x-vercel-ip-country from request headers (available on Vercel deployments)
  2. ISP – looks up client IP via ip-api.com or ipinfo.io
  3. User – optional 3rd source from auth metadata (set when user previously passed)

Access is allowed when at least 2 of 3 sources agree on an allowed country. If Vercel and ISP contradict (e.g. behind a proxy), access is blocked for safety.

Publishing

To publish to npm:

cd packages/next-geo-guard
npm run build
npm publish

Or use a scoped package: "name": "@yourorg/next-geo-guard" in package.json.

License

MIT