louisthomaspro / vercel-ip-blocking

Block IPs with Vercel's Edge Middleware and Edge Config

Home Page:https://vercel-ip-blocker.vercel.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Simple IP Blocker

DEMO: https://vercel-ip-blocker.vercel.app/

Using Edge Middleware, you can easily block IP addresses from accessing your site. This repo is using Next.js as an example.

Documentation

You can use Edge Middleware with any framework. To add Middleware to your app, you need to create a middleware.ts or middleware.js file in the root of your project.

Here is a simple example of how to block IP addresses:

// middleware.ts
import { ipAddress } from "@vercel/edge";
import { NextResponse } from "next/server";

export default async function middleware(request: Request) {
  const blockedIps = ["1.2.3.4", "5.6.7.8"];
  const ip = ipAddress(request);

  if (ip && blockedIps.includes(ip)) {
    return new NextResponse("Access denied", { status: 403 });
  }
}

The blockedIps variable can be configured using Edge Config to simplify the process of changing IP addresses.

  1. Create the Edge Config store

  2. Update the Edge Config store with the following JSON

{
  "blockedIps": [
    "1.2.3.4",
    "5.6.7.8"
  ]
}
  1. Update the middleware.ts file to use the get function from @vercel/edge-config
// middleware.ts
import { ipAddress } from "@vercel/edge";
import { NextResponse } from "next/server";
import { get } from "@vercel/edge-config";

export default async function middleware(request: Request) {
  const blockedIps = (await get("blockedIps")) as string[];
  const ip = ipAddress(request);

  if (ip && blockedIps.includes(ip)) {
    return new NextResponse("Access denied", { status: 403 });
  }
}

About

Block IPs with Vercel's Edge Middleware and Edge Config

https://vercel-ip-blocker.vercel.app


Languages

Language:TypeScript 86.4%Language:JavaScript 8.0%Language:CSS 5.6%