Organize/proxy.ts

32 lines
1.2 KiB
TypeScript

import { NextResponse } from "next/server";
import { auth } from "@/auth";
// Renamed from `middleware.ts` as of Next.js 16 ("Proxy"); same mechanism,
// still defaults to the Node.js runtime, so this can safely import the full
// Auth.js config. With JWT sessions, `auth()` only verifies the session
// cookie's signature here -- it never calls `authorize()` or hits the DB.
const PUBLIC_ROUTES = ["/login", "/signup"];
export default auth((req) => {
const isLoggedIn = !!req.auth;
const isPublicRoute = PUBLIC_ROUTES.includes(req.nextUrl.pathname);
if (!isLoggedIn && !isPublicRoute) {
return NextResponse.redirect(new URL("/login", req.nextUrl));
}
if (isLoggedIn && isPublicRoute) {
return NextResponse.redirect(new URL("/", req.nextUrl));
}
});
export const config = {
// Run on everything except static assets, image optimization, the auth
// API routes, and the PWA manifest/icons/service worker. sw.js must stay
// reachable regardless of auth state -- a redirected response for the
// service worker script itself is rejected by the browser outright.
matcher: [
"/((?!api/auth|_next/static|_next/image|favicon.ico|manifest.webmanifest|icons/|sw.js).*)",
],
};