-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.ts
58 lines (49 loc) · 1.69 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
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { getToken } from 'next-auth/jwt'
import { NextRequestWithAuth, withAuth } from 'next-auth/middleware'
async function middleware(request: NextRequest) {
// Handle socket.io routes first
if (request.nextUrl.pathname.startsWith('/api/socketio')) {
const response = NextResponse.next();
response.headers.append('Access-Control-Allow-Origin', '*');
response.headers.append('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
response.headers.append('Access-Control-Allow-Headers', 'Content-Type');
return response;
}
// Handle authentication for protected routes
if (request.nextUrl.pathname.startsWith('/dashboard') ||
request.nextUrl.pathname.startsWith('/login') ||
request.nextUrl.pathname.startsWith('/signup')) {
const token = await getToken({ req: request })
const isAuth = !!token
const isAuthPage = request.nextUrl.pathname.startsWith('/login') ||
request.nextUrl.pathname.startsWith('/signup')
if (isAuthPage) {
if (isAuth) {
return NextResponse.redirect(new URL('/dashboard', request.url))
}
return NextResponse.next()
}
if (!isAuth) {
let from = request.nextUrl.pathname;
if (request.nextUrl.search) {
from += request.nextUrl.search;
}
return NextResponse.redirect(
new URL(`/login?from=${encodeURIComponent(from)}`, request.url)
);
}
}
return NextResponse.next()
}
export default middleware
export const config = {
matcher: [
'/api/socketio/:path*',
'/dashboard/:path*',
'/login',
'/signup'
]
}