Skip to content

Commit e638d4f

Browse files
committed
Add a middleware layer, handle optimistic auth check on basic routes
1 parent c0889a9 commit e638d4f

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

src/lib/api/user-session.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export const loginUser = async (
2020
var userSession: UserSession = defaultUserSession();
2121
var err: string = "";
2222

23-
const data = await axios
23+
await axios
2424
.post(
2525
`${siteConfig.env.backendServiceURL}/login`,
2626
{
@@ -45,8 +45,8 @@ export const loginUser = async (
4545
// deserialize successfully, then downstream operations will see the default
4646
// userSessionData in state and we will experience subtle Bugs. We should consider
4747
// how best we want to handle this. Ex. clear auth cookie?
48-
console.debug("userSessionData: ", userSessionData)
49-
throw { message: 'Login Failed to produce valid User Session data' }
48+
console.debug("userSessionData: ", userSessionData);
49+
throw { message: "Login Failed to produce valid User Session data" };
5050
}
5151
})
5252
.catch(function (error: AxiosError) {
@@ -73,7 +73,7 @@ export const logoutUser = async (): Promise<string> => {
7373
const data = await axios
7474
.get(`${siteConfig.env.backendServiceURL}/logout`, {
7575
withCredentials: true,
76-
setTimeout: 5000, // 5 seconds before timing out trying to log in with the backend
76+
setTimeout: 5000, // 5 seconds before timing out trying to log out with the backend
7777
})
7878
.then(function (response: AxiosResponse) {
7979
// handle success

src/middleware.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { NextRequest, NextResponse } from "next/server";
2+
3+
// 1. Specify protected and public routes
4+
const protectedRoutes = [
5+
"/dashboard",
6+
"/coaching-sessions",
7+
"/settings",
8+
"/profile",
9+
];
10+
const publicRoutes = ["/"];
11+
12+
export default async function middleware(req: NextRequest) {
13+
// 2. Check if the current route is protected or public
14+
const path = req.nextUrl.pathname;
15+
const isProtectedRoute = protectedRoutes.includes(path);
16+
const isPublicRoute = publicRoutes.includes(path);
17+
18+
// 3. Decrypt the session from the cookie
19+
const sessionCookie = req.cookies.get("id");
20+
let session = sessionCookie?.value;
21+
22+
// 4. Redirect to / if the user is not authenticated
23+
if (isProtectedRoute && !session) {
24+
return NextResponse.redirect(new URL("/", req.nextUrl));
25+
}
26+
27+
// 5. Redirect to /dashboard if the user is authenticated
28+
if (
29+
isPublicRoute &&
30+
session &&
31+
!req.nextUrl.pathname.startsWith("/dashboard")
32+
) {
33+
return NextResponse.redirect(new URL("/dashboard", req.nextUrl));
34+
}
35+
36+
return NextResponse.next();
37+
}
38+
39+
// Routes Middleware should not run on
40+
export const config = {
41+
matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
42+
};

0 commit comments

Comments
 (0)