Authentication & Authorization

Updated 8 July 2026

The application uses JWT token-based authentication with cookie storage. This section covers the authentication flow, route protection, and admin authorization.

Authentication Flow

The authentication process follows these steps:

Login Implementation

"use client";

const response = await fetch("/api/login", { // Login with the given username and password
  method: "POST",
  body: JSON.stringify({ username, password })
});

const data = await response.json(); // Get data from response

if (data.success) {
  Cookies.set("token", data.data.token, { expires: 7 }); // Set token in cookies for 7 days
  router.push("/account");
}

Route Protection

// src/middleware.js
export function middleware(request) { // Middleware to check if user is authenticated
  const token = request.cookies.get("token")?.value;
  
  if (!token) {
    return NextResponse.redirect(new URL("/login", request.url)); // Redirect to login page if user is not authenticated
  }
  
  return NextResponse.next(); // Return next response
}

export const config = { // Config to match middleware for protected routes
  matcher: ["/account/:path*", "/checkout/:path*"]
};

Protected Routes

Routes matching the middleware pattern require authentication:

Note: You can add more routes to the matcher array to protect additional pages.

Checking Authentication Status

"use client";

const token = Cookies.get("token"); // Get token from cookies
if (!token) router.push("/login"); // Redirect to login page if user is not authenticated

Admin Authentication

const isAdmin = Cookies.get("admin") === "true"; // Check if user is admin
if (!isAdmin) router.push("/login"); // Redirect to login page if user is not admin

Logout Implementation

const handleLogout = () => {
  Cookies.remove("token");
  Cookies.remove("email");
  router.push("/login");
};

Registration & Password Reset

// Register
await fetch("/api/register", { // Register with the given email, password and username
  method: "POST",
  body: JSON.stringify({ email, password, username })
});

// Reset password
await fetch("/api/reset-password", { // Reset password with the given email
  method: "POST",
  body: JSON.stringify({ email })
});

// Change password
await fetch("/api/change-password", {
  method: "POST",
  body: JSON.stringify({ current_password, new_password })
});

Security Best Practices

Security Note: Never store sensitive data in localStorage. Always use httpOnly cookies for tokens.

Common Authentication Issues

Issue: Token not persisting

Solution: Check cookie settings (path, domain, sameSite). Ensure cookies are set correctly in API responses.

Issue: Redirect loops

Solution: Ensure login page is not in the middleware matcher. Check token validation logic.

Issue: Admin access denied

Solution: Verify admin cookie is set correctly. Check user permissions in WordPress.