Skip to content

Commit cb0dac0

Browse files
committed
Adjust middleware approach, using localstorage and reinitializing auth-store from localStorage
1 parent 76231e1 commit cb0dac0

File tree

3 files changed

+14
-6
lines changed

3 files changed

+14
-6
lines changed

src/lib/providers/auth-store-provider.tsx

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,13 @@ export interface AuthStoreProviderProps {
1616

1717
export const AuthStoreProvider = ({ children }: AuthStoreProviderProps) => {
1818
const storeRef = useRef<StoreApi<AuthStore>>(undefined);
19+
const authStore = localStorage.getItem("auth-store");
20+
21+
const persistedStoreOrNull = authStore ? JSON.parse(authStore).state : null;
22+
1923
if (!storeRef.current) {
20-
storeRef.current = createAuthStore();
24+
// storeRef.current = createAuthStore(authStore);
25+
storeRef.current = createAuthStore(persistedStoreOrNull);
2126
}
2227

2328
return (

src/lib/stores/auth-store.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ export const createAuthStore = (initState: AuthState = defaultInitState) => {
5050
}),
5151
{
5252
name: "auth-store",
53-
storage: createJSONStorage(() => sessionStorage),
53+
storage: createJSONStorage(() => localStorage),
5454
}
5555
)
5656
)

src/middleware.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,17 @@ const publicRoutes = ["/"];
1212
export default async function middleware(req: NextRequest) {
1313
// 2. Check if the current route is protected or public
1414
const path = req.nextUrl.pathname;
15-
const isProtectedRoute = protectedRoutes.includes(path);
16-
const isPublicRoute = publicRoutes.includes(path);
15+
const isProtectedRoute = protectedRoutes.some((route) =>
16+
path.startsWith(route)
17+
);
18+
const isPublicRoute = publicRoutes.some((route) => path === route);
1719

18-
// 3. Decrypt the session from the cookie
20+
// 3. Get the session from the cookie
1921
const sessionCookie = req.cookies.get("id");
2022
const session = sessionCookie?.value;
2123

2224
// 4. Redirect to / if the user is not authenticated
25+
// 4b. TODO: Check session validity/expiration?
2326
if (isProtectedRoute && !session) {
2427
return NextResponse.redirect(new URL("/", req.nextUrl));
2528
}
@@ -38,5 +41,5 @@ export default async function middleware(req: NextRequest) {
3841

3942
// Routes Middleware should not run on
4043
export const config = {
41-
matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
44+
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|.*\\.png$).*)"],
4245
};

0 commit comments

Comments
 (0)