Skip to content

Commit 4a77bae

Browse files
Merge pull request #128 from temisan0x/feat/middleware-protected-routes
feat: implement Next.js middleware for protected routes (#98)
2 parents aa847cc + 53ba028 commit 4a77bae

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

src/contexts/WalletContext.tsx

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,15 @@ async function fetchBalance(
7070
}
7171
}
7272

73+
function setWalletCookie() {
74+
document.cookie = "hasWallet=true; path=/; SameSite=Lax";
75+
}
76+
77+
function clearWalletCookie() {
78+
document.cookie = "hasWallet=; path=/; max-age=0";
79+
}
80+
81+
7382
export function WalletProvider({ children }: { children: ReactNode }) {
7483
const [state, setState] = useState<WalletState>({
7584
address: null,

src/middleware.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { NextResponse } from "next/server";
2+
import type { NextRequest } from "next/server";
3+
4+
export function middleware(request: NextRequest) {
5+
const { pathname } = request.nextUrl;
6+
7+
// Only protect authenticated routes; everything else passes through.
8+
const isProtectedRoute =
9+
pathname === "/dashboard" ||
10+
pathname.startsWith("/dashboard/") ||
11+
pathname === "/profile" ||
12+
pathname.startsWith("/profile/");
13+
14+
if (!isProtectedRoute) {
15+
return NextResponse.next();
16+
}
17+
18+
const hasWallet = request.cookies.get("hasWallet")?.value === "true";
19+
20+
if (!hasWallet) {
21+
return NextResponse.redirect(new URL("/", request.url));
22+
}
23+
24+
return NextResponse.next();
25+
}
26+
27+
export const config = {
28+
matcher: [
29+
// Ignore API routes and Next.js static assets for performance.
30+
"/((?!api|_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|.*\\..*).*)",
31+
],
32+
};

0 commit comments

Comments
 (0)