-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
68 lines (57 loc) · 1.74 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { createServerClient } from '@supabase/ssr';
import { NextRequest, NextResponse } from 'next/server';
export const config = {
matcher: [
'/((?!_next/static|_next/image|_vercel/|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
};
export const middleware = async (req: NextRequest) => {
let res = NextResponse.next({ request: { headers: req.headers } });
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return req.cookies.getAll();
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) =>
req.cookies.set(name, value),
);
res = NextResponse.next({ request: req });
cookiesToSet.forEach(({ name, value, options }) =>
res.cookies.set(name, value, options),
);
},
},
},
);
const user = await supabase.auth.getUser();
if (user.data.user) {
const forcePublic = ['/', '/forgot-password', '/sign-in', '/sign-up'];
if (forcePublic.includes(req.nextUrl.pathname)) {
return NextResponse.redirect(new URL('/subjects', req.url));
}
} else {
const forcePrivateStartsWith = [
'/account',
'/hey',
'/inbox',
'/inputs',
'/subjects',
'/teams',
'/templates',
];
if (
forcePrivateStartsWith.some((p) => req.nextUrl.pathname.startsWith(p))
) {
const inOrUp = req.nextUrl.pathname.includes('/join/') ? 'up' : 'in';
const redirect = `${req.nextUrl.pathname}${req.nextUrl.search}`;
return NextResponse.redirect(
new URL(`/sign-${inOrUp}?next=${redirect}`, req.url),
);
}
}
return res;
};