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:
Khalifa Fumo
2023-05-14 18:28:20 +03:00
committed by GitHub
parent 7c55446707
commit 1b97e659e0
+10 -1
View File
@@ -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
};