Shortlist / frontend /src /middleware.ts
Eren-Sama
Fix Google OAuth: add /auth/callback route, redirect to / instead of /login
aaa2d62
/** Route protection middleware: redirects unauthenticated users away from /dashboard/*. */
import { type NextRequest, NextResponse } from "next/server";
import { createServerClient } from "@supabase/ssr";
// Routes that require authentication (prefix match)
const PROTECTED_PREFIXES = ["/dashboard"];
// Routes that authenticated users should NOT see (redirect to dashboard)
const AUTH_ROUTES = ["/login", "/signup"];
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Create a Supabase server client that reads cookies from the request
let supabaseResponse = NextResponse.next({ request });
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value, options }) =>
request.cookies.set(name, value)
);
supabaseResponse = NextResponse.next({ request });
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options)
);
},
},
}
);
// Refresh the session (important for token rotation)
const {
data: { user },
} = await supabase.auth.getUser();
const isProtectedRoute = PROTECTED_PREFIXES.some((prefix) =>
pathname.startsWith(prefix)
);
const isAuthRoute = AUTH_ROUTES.some((route) => pathname.startsWith(route));
// Redirect unauthenticated users away from protected routes
if (isProtectedRoute && !user) {
const homeUrl = new URL("/", request.url);
homeUrl.searchParams.set("redirectTo", pathname);
return NextResponse.redirect(homeUrl);
}
// Redirect authenticated users away from auth pages
if (isAuthRoute && user) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
return supabaseResponse;
}
export const config = {
matcher: [
/*
* Match all routes except:
* - _next/static (static files)
* - _next/image (image optimization)
* - favicon.ico
* - public folder assets
*/
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};