-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
78 lines (52 loc) · 2.16 KB
/
middleware.js
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
69
70
71
72
73
74
75
76
77
78
import { NextResponse, NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
export default async function middleware(req) {
const session = await getToken({
req: req,
secret: process.env.NEXTAUTH_SECRET,
});
if(!session && !req.nextUrl.pathname.startsWith('/login') ) {
return NextResponse.redirect(new URL("/login", req.url));
}
else if(session && req.nextUrl.pathname.startsWith('/login')){
return NextResponse.redirect(new URL("/", req.url))
}
else if (!session && req.nextUrl.pathname === '/login') {
// This block handles the case where a user is already on the login page but not authenticated.
// You can add custom logic here if needed.
return;
} else if (!session && req.nextUrl.pathname.startsWith('/create-profile')) {
// This block handles the case where a user is on the create-profile page but not authenticated.
// You can add custom logic here if needed.
return;
}
// const userDetails = await fetch(`${process.env.NEXTAUTH_URL}/api/checkuser/${session?.email}`,{cache:'no-store'})
// const data = await userDetails.json();
// console.log("This is from middleware", data)
let data = null;
if (session) {
try {
const userDetailsResponse = await fetch(`${process.env.NEXTAUTH_URL}/api/checkuser/${session?.email}`);
if (userDetailsResponse.ok) {
data = await userDetailsResponse.json();
} else {
// Handle non-OK response, e.g., show an error page or redirect
console.error('User details fetch failed:', userDetailsResponse.status, userDetailsResponse.statusText);
}
} catch (error) {
console.error('Error fetching user details:', error);
}
}
if(!data?.user && !req.nextUrl.pathname.startsWith('/create-profile')){
return NextResponse.redirect(new URL("/create-profile", req.url))
}
else if(data?.user && req.nextUrl.pathname.startsWith('/create-profile')){
return NextResponse.redirect(new URL("/", req.url))
}
}
export const config = {
matcher:["/",'/login','/create-profile','/new-tweet','/api/checkuser','/api/trendingtweets'],
api: {
bodyParser: false, // Disable built-in bodyParser
},
};