Next.js integration for staging password protection middleware.
Edge Runtime compatible password protection for Next.js applications.
Try out our Next.js demo (password: demo
):
🚀 staging-next.vercel.app
npm install staging-next
# or
yarn add staging-next
# or
pnpm add staging-next
Create a middleware file in your Next.js project:
// middleware.ts
import staging from 'staging-next';
export const middleware = staging({
password: process.env.STAGING_PASSWORD,
siteName: "My Protected Site"
});
- Edge Runtime compatible
- Native Next.js middleware integration
- Cookie-based session handling
- Custom route matcher support
- No Node.js dependencies
See the main documentation for base options.
Additional options available for Next.js:
interface StagingNextOptions extends StagingOptions {
/** Custom matcher patterns for middleware */
matcher?: string[];
}
Configure which routes should be handled by the middleware:
export const middleware = staging({
password: process.env.STAGING_PASSWORD,
matcher: [
// Custom matcher patterns
"/((?!_next|public|api).*)",
],
publicRoutes: [
"^/public(/.*)?$",
"^/api/public(/.*)?$"
]
});
While we recommend using Nemo for a more robust authentication solution, according to Next.js documentation about nested middleware, you can also combine multiple middleware functions. Here's how to combine staging protection with your own authentication middleware to handle both password protection for staging environments and user authentication:
import { NextRequest, NextResponse } from "next/server";
import staging from "staging-next";
import { getToken } from "@/services/jwt";
// Your custom auth middleware implementation
async function authMiddleware(request: NextRequest) {
// Add your auth logic here
return NextResponse.redirect(new URL("/auth", request.url));
}
// Routes that require authentication
const authMiddlewareMatcher = [
"/dashboard",
"/settings",
"/checkout",
];
// Configure staging middleware
const stagingMiddleware = staging({
siteName: "My Protected Site",
});
// Combined middleware function
export function middleware(request: NextRequest) {
if (authMiddlewareMatcher.some((path) =>
request.nextUrl.pathname.startsWith(path)
)) {
return authMiddleware(request);
}
return stagingMiddleware(request);
}
A complete working example is available in our repository: