mirror of
https://github.com/supabase/supabase.git
synced 2026-10-06 01:45:10 +03:00
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.
22 lines
850 B
TypeScript
22 lines
850 B
TypeScript
import { createMiddlewareSupabaseClient } from "@supabase/auth-helpers-nextjs";
|
|
import { NextResponse } from "next/server";
|
|
|
|
import type { NextRequest } from "next/server";
|
|
import type { Database } from "./lib/database.types";
|
|
|
|
export async function middleware(req: NextRequest) {
|
|
const res = NextResponse.next();
|
|
const supabase = createMiddlewareSupabaseClient<Database>({ req, res });
|
|
|
|
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
|
|
};
|