-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
46 lines (35 loc) · 1.66 KB
/
Copy pathmiddleware.ts
File metadata and controls
46 lines (35 loc) · 1.66 KB
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
// File: middleware.ts
// Edge middleware for route protection.
// In a real app, this would verify JWT/session tokens.
// Here we simulate auth by checking a cookie flag.
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
// Routes that require authentication
const PROTECTED_ROUTES = ["/app", "/onboarding"];
// Safe redirect destinations — whitelist pattern prevents open redirect attacks
const SAFE_REDIRECTS = ["/auth/sign-in", "/auth/sign-up", "/", "/onboarding"];
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Check if the route requires authentication
const isProtected = PROTECTED_ROUTES.some((route) => pathname.startsWith(route));
if (isProtected) {
// In a real app, verify session/JWT here.
// For demo purposes, we check for a mock auth cookie.
const isAuthenticated = request.cookies.get("auth-token")?.value;
if (!isAuthenticated) {
// Redirect to sign-in with the intended destination
const signInUrl = new URL("/auth/sign-in", request.url);
// Only set redirect param if destination is in our whitelist
// This prevents open redirect attacks
if (SAFE_REDIRECTS.includes(pathname) || pathname.startsWith("/app")) {
signInUrl.searchParams.set("redirect", pathname);
}
return NextResponse.redirect(signInUrl);
}
}
return NextResponse.next();
}
export const config = {
// Match all routes except static files, api routes, and Next.js internals
matcher: ["/((?!_next/static|_next/image|favicon.ico|api).*)"],
};