-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
55 lines (45 loc) · 1.67 KB
/
middleware.js
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
47
48
49
50
51
52
53
54
55
import createMiddleware from "next-intl/middleware";
import { NextResponse } from "next/server";
const isAuthenticated = (request) => {
const token = request.cookies.get("user"); // Adjust the key based on your token storage method
console.log("Access Token:", token); // Log the token for debugging
return token; // Return true if authenticated, false otherwise
};
const intlMiddleware = createMiddleware({
locales: ["en", "de", "hi"],
defaultLocale: "en",
});
export function middleware(request) {
const cookies = request.cookies;
console.log("All cookies:", cookies);
const token = cookies["user"] || null; // Accessing directly using the bracket notation
console.log("Access Token:", token);
console.log("Middleware executed on path:", request.nextUrl.pathname);
const protectedRoutes = [
"/en/profile",
"/hi/profile",
"/de/profile",
"/en/cart",
"/hi/cart",
"/de/cart",
]; // Add your protected routes here
const isProtectedRoute = protectedRoutes.some((route) =>
request.nextUrl.pathname.startsWith(route)
);
console.log("Is protected route:", isProtectedRoute);
if (isProtectedRoute) {
const authenticated = isAuthenticated(request);
console.log("User authenticated:", authenticated);
if (!authenticated) {
console.log("Redirecting to login");
// Redirect to login with a query parameter indicating the error
return NextResponse.redirect(
new URL("/?error=not_authenticated", request.url)
); // Adjust the URL based on your login route
}
}
return intlMiddleware(request);
}
export const config = {
matcher: ["/", "/(de|en|hi)/:path*"], // Match all locales and specific paths
};