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
Maintainers
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-setupQuick 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?: stringfor 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(defaulttrue).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, default100).cookieName?: string– defaultab_${experimentName}.cookieMaxAgeDays?: number(default30).
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.
