Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Update middleware.ts to check if user is logged in

Khalifa Fumo1b97e659e008
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<Database>({ 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
+};