Share

Next.js middleware that protects routes and keeps the session fresh

Open · 5 views · asked by sven_fire · edited

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
// 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*"] };
Comment

Activity