Two things at once: the redirect for signed-out visitors, and the cookie refresh that stops people being logged out after an hour. Use getUser, not getSession: getSession trusts the cookie without verifying it.
Snippet Copied 8 times Copy // middleware.ts
import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";
export async function middleware(request: NextRequest) {
const response = NextResponse.next({ request });
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll: () => request.cookies.getAll(),
setAll: (cookies) =>
cookies.forEach(({ name, value, options }) =>
response.cookies.set(name, value, options)
),
},
}
);
const { data } = await supabase.auth.getUser();
if (!data.user) {
return NextResponse.redirect(new URL("/login", request.url));
}
return response;
}
export const config = { matcher: ["/app/:path*"] };