mirror of
https://github.com/supabase/supabase.git
synced 2026-05-06 08:56:46 -04:00
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.
This commit is contained in:
@@ -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
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user