Implement robust authentication and authorization using Next.js middleware with JWT, session management, and protected routes.
# Next.js Middleware & Authentication for Google Antigravity
Master Next.js middleware and authentication patterns in your Google Antigravity projects. This guide covers route protection, JWT validation, role-based access, and session management.
## Middleware Configuration
Create comprehensive authentication middleware:
```typescript
// middleware.ts
import { NextRequest, NextResponse } from "next/server";
import { jwtVerify } from "jose";
// Route configuration
const PUBLIC_ROUTES = ["/", "/login", "/signup", "/forgot-password", "/reset-password"];
const AUTH_ROUTES = ["/login", "/signup"];
const API_AUTH_ROUTES = ["/api/auth/login", "/api/auth/signup", "/api/auth/refresh"];
const ADMIN_ROUTES = ["/admin", "/admin/users", "/admin/settings"];
// JWT verification
async function verifyToken(token: string): Promise<{ userId: string; role: string } | null> {
try {
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
const { payload } = await jwtVerify(token, secret);
return {
userId: payload.userId as string,
role: payload.role as string,
};
} catch {
return null;
}
}
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Skip middleware for static files and Next.js internals
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/static") ||
pathname.includes(".") // Files with extensions
) {
return NextResponse.next();
}
// Get tokens from cookies
const accessToken = request.cookies.get("access_token")?.value;
const refreshToken = request.cookies.get("refresh_token")?.value;
// Verify access token
let user = accessToken ? await verifyToken(accessToken) : null;
// Try to refresh if access token is invalid
if (!user && refreshToken) {
try {
const refreshResponse = await fetch(
new URL("/api/auth/refresh", request.url),
{
method: "POST",
headers: {
Cookie: `refresh_token=${refreshToken}`,
},
}
);
if (refreshResponse.ok) {
const data = await refreshResponse.json();
user = await verifyToken(data.accessToken);
// Create response with new tokens
const response = NextResponse.next();
response.cookies.set("access_token", data.accessToken, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 60 * 15, // 15 minutes
});
if (data.refreshToken) {
response.cookies.set("refresh_token", data.refreshToken, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 60 * 60 * 24 * 7, // 7 days
});
}
// Continue with the refreshed token
return handleRouteAccess(request, user, response);
}
} catch {
// Refresh failed, clear tokens
const response = NextResponse.redirect(new URL("/login", request.url));
response.cookies.delete("access_token");
response.cookies.delete("refresh_token");
return response;
}
}
return handleRouteAccess(request, user);
}
function handleRouteAccess(
request: NextRequest,
user: { userId: string; role: string } | null,
response?: NextResponse
): NextResponse {
const { pathname } = request.nextUrl;
const res = response || NextResponse.next();
// Handle API routes
if (pathname.startsWith("/api/")) {
// Allow public API routes
if (API_AUTH_ROUTES.some((route) => pathname.startsWith(route))) {
return res;
}
// Require authentication for other API routes
if (!user) {
return NextResponse.json(
{ error: "Unauthorized" },
{ status: 401 }
);
}
// Add user info to headers for API routes
res.headers.set("x-user-id", user.userId);
res.headers.set("x-user-role", user.role);
return res;
}
// Redirect authenticated users away from auth pages
if (user && AUTH_ROUTES.some((route) => pathname === route)) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
// Allow public routes
if (PUBLIC_ROUTES.some((route) => pathname === route)) {
return res;
}
// Require authentication for protected routes
if (!user) {
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("redirect", pathname);
return NextResponse.redirect(loginUrl);
}
// Check admin access
if (ADMIN_ROUTES.some((route) => pathname.startsWith(route))) {
if (user.role !== "admin") {
return NextResponse.redirect(new URL("/unauthorized", request.url));
}
}
return res;
}
export const config = {
matcher: [
/*
* Match all paths except:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder
*/
"/((?!_next/static|_next/image|favicon.ico|public/).*)",
],
};
```
## Authentication API Routes
Implement secure authentication endpoints:
```typescript
// src/app/api/auth/login/route.ts
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import bcrypt from "bcryptjs";
import { SignJWT } from "jose";
import { db } from "@/lib/database";
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(1),
rememberMe: z.boolean().optional(),
});
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { email, password, rememberMe } = loginSchema.parse(body);
// Find user
const user = await db.user.findUnique({
where: { email },
select: {
id: true,
email: true,
name: true,
password: true,
role: true,
status: true,
},
});
if (!user) {
return NextResponse.json(
{ error: "Invalid credentials" },
{ status: 401 }
);
}
// Check password
const isValid = await bcrypt.compare(password, user.password);
if (!isValid) {
return NextResponse.json(
{ error: "Invalid credentials" },
{ status: 401 }
);
}
// Check account status
if (user.status !== "active") {
return NextResponse.json(
{ error: "Account is not active" },
{ status: 403 }
);
}
// Generate tokens
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
const accessToken = await new SignJWT({
userId: user.id,
email: user.email,
role: user.role,
})
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("15m")
.sign(secret);
const refreshToken = await new SignJWT({
userId: user.id,
type: "refresh",
})
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime(rememberMe ? "30d" : "7d")
.sign(secret);
// Store refresh token in database
await db.refreshToken.create({
data: {
token: refreshToken,
userId: user.id,
expiresAt: new Date(Date.now() + (rememberMe ? 30 : 7) * 24 * 60 * 60 * 1000),
},
});
// Create response with cookies
const response = NextResponse.json({
user: {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
},
});
response.cookies.set("access_token", accessToken, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 60 * 15,
});
response.cookies.set("refresh_token", refreshToken, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: (rememberMe ? 30 : 7) * 24 * 60 * 60,
});
return response;
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: "Validation failed", details: error.errors },
{ status: 400 }
);
}
console.error("Login error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
```
## Protected Page Components
Create authentication-aware components:
```typescript
// src/components/auth/withAuth.tsx
"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
interface WithAuthOptions {
requiredRole?: "user" | "admin";
redirectTo?: string;
}
export function withAuth<P extends object>(
Component: React.ComponentType<P>,
options: WithAuthOptions = {}
) {
const { requiredRole, redirectTo = "/login" } = options;
return function ProtectedComponent(props: P) {
const router = useRouter();
const { user, isLoading, isAuthenticated } = useAuth();
useEffect(() => {
if (!isLoading && !isAuthenticated) {
router.push(`${redirectTo}?redirect=${window.location.pathname}`);
}
if (!isLoading && isAuthenticated && requiredRole) {
if (user?.role !== requiredRole) {
router.push("/unauthorized");
}
}
}, [isLoading, isAuthenticated, user, router]);
if (isLoading) {
return (
<div className="flex min-h-screen items-center justify-center">
<div className="h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" />
</div>
);
}
if (!isAuthenticated) {
return null;
}
if (requiredRole && user?.role !== requiredRole) {
return null;
}
return <Component {...props} />;
};
}
// Usage
const AdminDashboard = withAuth(DashboardComponent, { requiredRole: "admin" });
```
Google Antigravity generates comprehensive Next.js authentication with middleware protection, JWT handling, and role-based access control for secure applications.This Next.js prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their next.js implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Next.js projects, consider mentioning your framework version, coding style, and any specific libraries you're using.