UNPKG

logicloom-nextjs-starter

Version:

A production-ready Next.js starter template with authentication, i18n, dark mode, and modern patterns

43 lines (35 loc) 1.46 kB
import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; export function middleware(request: NextRequest) { const { pathname } = request.nextUrl; // Check if user has auth token (from cookies) const authToken = request.cookies.get("auth_token"); const isAuthenticated = !!authToken?.value; // If user is authenticated and trying to access /auth page, redirect to home if (isAuthenticated && pathname === "/auth") { return NextResponse.redirect(new URL("/", request.url)); } // If user is not authenticated and trying to access protected routes, redirect to auth // You can add more protected routes here if needed const protectedRoutes = ["/dashboard", "/profile", "/settings"]; const isProtectedRoute = protectedRoutes.some((route) => pathname.startsWith(route) ); if (!isAuthenticated && isProtectedRoute) { return NextResponse.redirect(new URL("/auth", request.url)); } return NextResponse.next(); } // Configure which paths the middleware should run on export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico, sitemap.xml, robots.txt (metadata files) */ "/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)", ], };