Skip to main content

Version: v1

Protected Routes Validation

To ensure security and a seamless user experience, UniSouk provides a way to validate user sessions for protected routes using the /auth/refresh/{storeId} API. This helps confirm if a user is still authenticated based on the HTTP-only refresh token.


🔍 Why This Is Needed

  • Prevent unauthorized users from accessing secured pages (e.g., profile, dashboard, checkout)
  • Maintain user sessions across page reloads or navigation
  • Seamlessly re-authenticate users in the background without requiring login prompts

🔧 Implementation

Use the GET /auth/refresh/{storeId} endpoint to verify the user's authentication state. This call checks the validity of the refresh token stored in a secure HTTP-only cookie and returns a new access token if the session is valid.


🔐 Example in React

Step 1: Create Auth Check Helper

// authGuard.ts
import { api, setAccessToken } from "../constant";

export const checkAuthentication = async () => {
try {
const response = await api.get(`/auth/refresh/<STORE_ID>`);
const newAccessToken = response.data.data.accessToken;
setAccessToken(newAccessToken);
return true;
} catch (error) {
console.error("Auth check failed:", error);
return false;
}
};

Step 2: Use in Route-Level Logic

// ProtectedPage.tsx
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { checkAuthentication } from "../auth/authGuard";

const ProtectedPage = () => {
const navigate = useNavigate();

useEffect(() => {
const validate = async () => {
const isAuthenticated = await checkAuthentication();
if (!isAuthenticated) {
navigate("/auth/login");
}
};

validate();
}, []);

return <div>🔐 Protected Content</div>;
};

export default ProtectedPage;

🧠 Best Practices

  • Always run this check before rendering sensitive content.
  • You may optionally store the authentication state in React context or global state to reduce redundant checks.
  • For server-rendered apps (Next.js, Remix), consider running the check in middleware or loaders.