-
Notifications
You must be signed in to change notification settings - Fork 2
/
middleware.ts
62 lines (54 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
import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs';
import { NextRequest, NextResponse } from 'next/server';
/**
* Next.js middleware
*
* @param req
* @returns
*
* https://nextjs.org/docs/app/building-your-application/routing/middleware
* Middleware allows you to run code before a request is completed. Then, based on the incoming request,
* you can modify the response by rewriting, redirecting, modifying the request or response headers,
* or responding directly.
*
*/
export async function middleware(req: NextRequest) {
const res = NextResponse.next();
const supabase = createMiddlewareClient({ req, res });
const {
data: { user },
} = await supabase.auth.getUser();
/**
* AUTHENTICATED USER REDIRECTS
*/
if (user) {
if (req.nextUrl.pathname === '/login') {
if (process.env.NODE_ENV === 'development') {
console.log('Redirecting authenticated user from /login to /account');
}
return NextResponse.redirect(new URL('/account', req.url));
}
}
/**
* UNAUTHENTICATED USER REDIRECTS
*/
if (!user) {
if (req.nextUrl.pathname == '/submit') {
if (process.env.NODE_ENV === 'development') {
console.log('Redirecting unauthenticated user from /submit to /login');
}
return NextResponse.redirect(new URL('/login', req.url));
}
if (req.nextUrl.pathname == '/account') {
if (process.env.NODE_ENV === 'development') {
console.log('Redirecting unauthenticated user from /account to /login');
}
return NextResponse.redirect(new URL('/login', req.url));
}
}
return res;
}
// Config tells Next.js which routes to apply the middleware to
export const config = {
matcher: ['/', '/account', '/login', '/submit'],
};