Skip to main content

Auth Guard

The authGuard function is employed to regulate access to specific routes based on user authentication status. For instance, the loginGuard function, redirects authenticated users from certain pages such as 'login' and 'register', while the isLoggedIn function restricts access to the PageWithLoginCheck page solely to authenticated users.

The below examples shows how authGuard functions like loginGuard and isLoggedIn are utilized to control access to routes based on user authentication status:

1. Implementation of loginGuard Function

import React from 'react';
import PageWithAuthGuard from '../page-layouts/PageWithAuthGuard';
const loginGuard= ({ fpi, store, redirectUrl }) => {
try {
const loggedIn = await isLoggedIn({ fpi, store });
if (loggedIn) {
if (isRunningOnClient()) {
window.location.navigate(redirectUrl ?? "/");
}
return;
}
} catch (error) {
return true;
}
}

function PageWithAuthGuard({ fpi }) {
return (
<>
<PageWithAuthGuard fpi={fpi}>
</PageWithAuthGuard>
</>
);
}
PageWithAuthGuard.authGuard = loginGuard;
export default RegisterPage;

2. Implementation of isLoggedIn Function

import React from 'react';
import { isLoggedIn } from '../helper/auth-guard';
import Cart from '../page-layouts/cart/cart';

const isLoggedIn = ({ fpi, store }) => {
const userFetched = store?.auth?.user_fetched ?? false;
if (userFetched) {
const loggedIn = store?.auth?.logged_in;
return loggedIn;
}

const { payload } = await fpi.auth.fetchUserData();
return !!(payload?.user ?? false);
}

function PageWithLoginCheck({ fpi }) {
return (
<>
<PageWithLoginCheck fpi={fpi} />
</>
);
}
PageWithLoginCheck.serverFetch = () => { };
PageWithLoginCheck.authGuard = isLoggedIn;
export default PageWithLoginCheck;

Was this section helpful?