-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmiddleware.ts
30 lines (26 loc) · 1.02 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { createMiddlewareClient } from "@supabase/auth-helpers-nextjs";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export async function middleware(req: NextRequest) {
// We need to create a response and hand it to the supabase client to be able to modify the response headers.
const res = NextResponse.next();
// Create authenticated Supabase Client.
const supabase = createMiddlewareClient({ req, res });
// Check if we have a session
const {
data: { session },
} = await supabase.auth.getSession();
// Check auth condition
if (session?.user) {
// Authentication successful, forward request to protected route.
return res;
}
// Auth condition not met, redirect to login page.
const redirectUrl = req.nextUrl.clone();
redirectUrl.pathname = "/signin";
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname);
return NextResponse.redirect(redirectUrl);
}
export const config = {
matcher: ["/admin/:path*", "/api/admin/:path*"],
};