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

nextjs-middleware-setup

v0.1.3

Published

Next.js middleware & Edge runtime utilities for auth, IP restriction, bot detection, A/B testing, and rewrites with full TypeScript support.

Downloads

26

Readme

nextjs-middleware-setup

Edge-ready utilities for Next.js middleware and the Edge runtime: auth guard, IP restriction, bot detection, A/B testing, and rewrite helpers, all with strict TypeScript support. All helpers are tree-shakable and rely only on Web Standard APIs, making them safe for the Edge runtime.

Installation

npm install nextjs-middleware-setup
# or
yarn add nextjs-middleware-setup
# or
pnpm add nextjs-middleware-setup

Quick Start (Next.js middleware)

// middleware.ts
import { NextRequest, NextResponse } from "next/server";
import { authGuard, ipRestriction, isBot, abTest, buildRewriteUrl } from "nextjs-middleware-setup";

export async function middleware(req: NextRequest) {
  // 1) Auth guard (e.g. protect /dashboard)
  if (req.nextUrl.pathname.startsWith("/dashboard")) {
    const auth = await authGuard(req, {
      cookieName: "auth_token",
      redirectTo: "/login"
    });

    if (!auth.isAuthorized) {
      if (auth.redirectUrl) {
        return NextResponse.redirect(auth.redirectUrl);
      }

      return new NextResponse("Unauthorized", { status: auth.status });
    }
  }

  // 2) IP restriction example
  const ipCheck = ipRestriction(req, {
    mode: "blocklist",
    blockedIps: ["192.168.0.10"]
  });

  if (!ipCheck.isAllowed) {
    return new NextResponse("Forbidden", { status: 403 });
  }

  // 3) Bot detection
  const bot = isBot(req);
  if (bot.isBot) {
    // Optionally short-circuit for bots
    return NextResponse.next();
  }

  // 4) A/B test
  const ab = abTest(req, {
    experimentName: "homepage-layout",
    variants: ["control", "variantA"],
    rolloutPercentage: 50
  });

  const res = NextResponse.next();
  if (ab.cookie) {
    res.headers.append("Set-Cookie", ab.cookie.headerValue);
  }

  // 5) Rewrite helper
  if (req.nextUrl.pathname === "/legacy") {
    const target = buildRewriteUrl(req, "/new-legacy", { preserveQuery: true });
    return NextResponse.rewrite(target);
  }

  return res;
}

export const config = {
  matcher: ["/:path*"]
};

API Overview

authGuard(req, options)

Small helper to check for a token in cookies or headers and optionally validate it.

  • Options:

    • cookieName?: string – cookie to read token from (default "auth_token").
    • headerName?: string – header name if you prefer header-based token (e.g. "authorization").
    • bearerPrefix?: string – default "Bearer ".
    • getToken?: (req) => string | null – custom token extractor.
    • validateToken?: (token) => boolean | Promise<boolean> – custom token validation (JWT, etc.).
    • redirectTo?: string – URL to redirect on failure (302 instead of 401).
  • Returns:

    • { isAuthorized: true; token?: string | null } or
    • { isAuthorized: false; status: 401 | 302; redirectUrl?: string; reason: string }.

ipRestriction(req, options)

Whitelist/blacklist IP helper.

  • mode: "allowlist" | "blocklist" (default "blocklist").
  • allowedIps?: string[], blockedIps?: string[].
  • headerName?: string for IP (default "x-forwarded-for").
  • Returns { isAllowed: boolean; ip?: string | null; reason?: string }.

buildRewriteUrl(req, target, options?)

Builds a URL for rewrite/redirect, preserving and merging query parameters.

  • target: string – absolute or relative path.
  • options.preserveQuery?: boolean (default true).
  • options.mergeQuery?: Record<string, string | undefined> – extra query params.

isBot(req, options?)

Fast user-agent/header-based bot detection.

  • Uses common bot user-agent substrings.
  • Options allow extra allowlist/blocklist regexes.
  • Returns { isBot: boolean; matchedRule?: string; userAgent: string }.

abTest(req, options)

Cookie-based A/B test assignment.

  • experimentName: string.
  • variants: string[] – e.g. ["control", "variant"].
  • rolloutPercentage?: number (0–100, default 100).
  • cookieName?: string – default ab_${experimentName}.
  • cookieMaxAgeDays?: number (default 30).

Returns:

{
  variant: string;
  isNewAssignment: boolean;
  cookie?: {
    name: string;
    value: string;
    headerValue: string; // ready-to-use Set-Cookie value
  };
}

Usage in middleware:

const res = NextResponse.next();
if (ab.cookie) {
  res.headers.append("Set-Cookie", ab.cookie.headerValue);
}

Development

  • Build: npm run build
  • Test: npm test
  • Lint: npm run lint
  • Typecheck: npm run typecheck
  • Example app: npm run example:dev

See the bottom of this document for linking/publishing instructions.