-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
70 lines (54 loc) · 2.02 KB
/
Copy pathmiddleware.js
File metadata and controls
70 lines (54 loc) · 2.02 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { createI18nMiddleware } from "next-international/middleware";
import { getCartMiddleware } from "@/lib/cart";
// Define the cart validation middleware
async function cartMiddleware(request) {
// 1. Check if the cookies has the cart id
const storeCookies = await cookies();
const hasCartId = storeCookies.has("cartId");
if (!hasCartId) {
return NextResponse.redirect(new URL("/", request.url));
}
// 2. Get the cart id
const cartId = storeCookies.get("cartId").value;
// 3. Fetch cart data
const { data, errors } = await getCartMiddleware(cartId);
// 4. Check if there errors
if (errors) {
return NextResponse.redirect(new URL("/", request.url));
}
// 5. Check if the cart is NOT empty
if (data.cart.lines.nodes.length === 0) {
return NextResponse.redirect(new URL("/", request.url));
}
return NextResponse.next();
}
// Create the I18n middleware
const I18nMiddleware = createI18nMiddleware({
locales: ["en", "fr"],
defaultLocale: "en",
});
// Combined middleware function
export async function middleware(request) {
const pathname = request.nextUrl.pathname;
// Check if the path starts with a locale
const localePattern = /^\/(en|fr|ar)(\/|$)/;
if (!localePattern.test(pathname) && pathname.startsWith("/checkout")) {
// Redirect to default locale (e.g., /en/checkout)
return NextResponse.redirect(new URL(`/en${pathname}`, request.url));
}
// Apply the internationalization middleware
const i18nResponse = I18nMiddleware(request);
// Check if it's a checkout page
const isCheckoutPage = pathname.endsWith("/checkout");
// Apply cart validation only for checkout pages after i18n processing
if (isCheckoutPage) {
return cartMiddleware(request);
}
return i18nResponse;
}
export const config = {
// Match both internationalized pathnames and checkout paths, excluding static files and API routes
matcher: ["/((?!api|static|.*\\..*|_next|favicon.ico|robots.txt).*)"],
};