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:
- User submits login form User enters username/email and password on the login page
- Frontend sends credentials Credentials are sent to
/api/loginendpoint - API route authenticates API route validates credentials with WordPress REST API
- JWT token returned If valid, a JWT token is returned along with user information
- Token stored in cookies Token is stored in httpOnly cookies for security
- Middleware validates Middleware checks token for protected routes on each request
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:
/account/*– User account pages/orders/*– Order history and details/dashboard/*– User dashboard/checkout/*– Checkout process
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 authenticatedAdmin 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 adminLogout 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
- Use httpOnly Cookies: Prevents XSS attacks
- Set Secure Flag: Only send cookies over HTTPS in production
- Set SameSite: Prevents CSRF attacks
- Validate on Server: Always validate tokens server-side
- Token Expiration: Set reasonable token expiration times
- Password Hashing: Never store plain text passwords
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.
Next Steps: Learn about Cart Management and Checkout Process which also use authentication.