From 1b97e659e00819198fed13374d13d4b844c67f5a Mon Sep 17 00:00:00 2001 From: Khalifa Fumo <72398188+khalifa47@users.noreply.github.com> Date: Sun, 14 May 2023 18:28:20 +0300 Subject: [PATCH] Update middleware.ts to check if user is logged in I was experiencing an issue where I could not protect my routes within my Next.js 13 (app) app. I searched for a fix everywhere but the app router being a new development, I did not find any help, even within the supabase docs, so I set out to trying a fix for myself and I found this to work perfectly. You can now protect your routes such that only logged in users can access some pages. You can also configure the config such that the middleware is set to run (or not to run) on selected pages. --- examples/auth/nextjs/middleware.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/examples/auth/nextjs/middleware.ts b/examples/auth/nextjs/middleware.ts index 24b65f84742..e775a9d9931 100644 --- a/examples/auth/nextjs/middleware.ts +++ b/examples/auth/nextjs/middleware.ts @@ -7,6 +7,15 @@ import type { Database } from "./lib/database.types"; export async function middleware(req: NextRequest) { const res = NextResponse.next(); const supabase = createMiddlewareSupabaseClient({ req, res }); - await supabase.auth.getSession(); + + const { data: { session } } = await supabase.auth.getSession(); // destructure the data object to obtain the session object + + if (session === null) return NextResponse.redirect(new URL("/login", req.nextUrl)); + // instead of "/login" you can redirect to any other route in case the user is not logged in + return res; } + +export const config = { + matcher: [], // add the routes you wish the middleware to run in. You can also use regex +};