-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
34 lines (27 loc) · 1.1 KB
/
middleware.ts
File metadata and controls
34 lines (27 loc) · 1.1 KB
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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// This middleware is used to handle authentication redirects
export async function middleware(req: NextRequest) {
const res = NextResponse.next();
// Get the pathname
const { pathname } = req.nextUrl;
// Auth routes that don't require authentication
const authRoutes = ['/login', '/signup'];
// Check if there's a session cookie - Supabase uses cookies that start with 'sb-'
// We need to check for access token and refresh token
const hasSupabaseCookies = Array.from(req.cookies.getAll())
.some(cookie =>
(cookie.name.startsWith('sb-') && cookie.name.includes('auth')) ||
cookie.name.includes('access_token') ||
cookie.name.includes('refresh_token')
);
// If the user is on an auth route but is already authenticated, redirect to home
if (authRoutes.includes(pathname) && hasSupabaseCookies) {
return NextResponse.redirect(new URL('/', req.url));
}
return res;
}
// Only run the middleware on specific routes
export const config = {
matcher: ['/login', '/signup'],
};