-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmiddleware.ts
More file actions
50 lines (42 loc) · 1.56 KB
/
middleware.ts
File metadata and controls
50 lines (42 loc) · 1.56 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// This middleware can be reused in other Next.js projects by:
// 1. Copying this file to your project's root directory
// 2. Adjusting the public paths and matcher config as needed
// 3. Ensuring next-auth is properly configured in your project
export function middleware(request: NextRequest) {
// Get the pathname of the request
const path = request.nextUrl.pathname;
// Define public paths that don't require authentication
// Customize these paths based on your project's auth routes
const isPublicPath = path === '/auth/login' || path === '/auth/register';
// Get the token from cookies - handle both production and development environments
const token =
request.cookies.get('next-auth.session-token')?.value ||
request.cookies.get('__Secure-next-auth.session-token')?.value ||
'';
// Redirect authenticated users away from auth pages
if (isPublicPath && token) {
return NextResponse.redirect(new URL('/', request.url));
}
// Allow access to public paths
if (isPublicPath) {
return NextResponse.next();
}
// Redirect unauthenticated users to login
if (!token) {
return NextResponse.redirect(new URL('/auth/login', request.url));
}
// Allow authenticated users to access protected routes
return NextResponse.next();
}
// Configure protected routes - customize for your project
export const config = {
matcher: [
'/workspace/:path*',
'/auth/login',
'/auth/register',
'/settings/:path*',
'/profile/:path*',
],
};