-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
43 lines (38 loc) · 1.5 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
//keep the file name middleware.ts only not anything else it will not work as it is nextjs specific
import authConfig from "./auth.config";
import NextAuth from "next-auth";
import { apiAuthPrefix, authRoutes, publicRoutes } from "./routes";
import { getDefaultLoginRedirect } from "@/data/getUserId";
const { auth } = NextAuth(authConfig);
export default auth(async (req) => {
const { nextUrl } = req;
const isLoggedIn = !!req.auth;
const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
const isAuthRoute = authRoutes.includes(nextUrl.pathname);
if (isApiAuthRoute) {
return;
}
if (isAuthRoute) {
if (isLoggedIn) {
return Response.redirect(
new URL(await getDefaultLoginRedirect(), nextUrl)
);
}
return;
}
if (!isLoggedIn && !isPublicRoute) {
let callbackUrl = nextUrl.pathname;
if (nextUrl.search) {
callbackUrl = nextUrl.search;
}
const encodedCallbackUrl = encodeURIComponent(callbackUrl);
return Response.redirect(
new URL(`/auth/login?callbackUrl=${encodedCallbackUrl}`, nextUrl)
);
}
return;
});
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"], //its helps finding the currrunt route we are doing this because at first we will access all the routes at start and then in the middleware we will just seperate them into public and private routed. All the route accessed here is passes to the above function
};