useIsAuthenticated is a hook that calls the check method from the authProvider under the hood. It returns a query result from @tanstack/react-query.
Usage
import { useIsAuthenticated } from "@refinedev/core";
const { data, isLoading } = useIsAuthenticated();
if (isLoading) {
return <div>Loading...</div>;
}
if (data?.authenticated) {
return <div>User is authenticated</div>;
}
Parameters
Options to configure the query from @tanstack/react-query.Enable or disable the query.
queryOptions.retry
boolean | number
default:"false"
Retry configuration for failed queries.
Callback function to be called when the query succeeds.
Callback function to be called when the query fails.
Additional metadata to pass to the query.
Additional parameters to pass to the authProvider.check method.
Return Values
Returns a query result from @tanstack/react-query.
The authentication check response.Indicates whether the user is authenticated.
The URL to redirect to if not authenticated.
Indicates whether the user should be logged out.
Error object if authentication check failed.
Indicates whether the query is loading.
Indicates whether the query is fetching.
Indicates whether the query was successful.
Indicates whether the query encountered an error.
Error object if the query failed.
A function to manually refetch the query.
Examples
Basic Usage
import { useIsAuthenticated } from "@refinedev/core";
const ProtectedComponent = () => {
const { data, isLoading } = useIsAuthenticated();
if (isLoading) {
return <div>Checking authentication...</div>;
}
if (!data?.authenticated) {
return <div>Please log in to access this content</div>;
}
return <div>Protected content</div>;
};
Conditional Rendering
import { useIsAuthenticated } from "@refinedev/core";
import { LoginButton } from "./LoginButton";
import { UserProfile } from "./UserProfile";
const Header = () => {
const { data } = useIsAuthenticated();
return (
<header>
{data?.authenticated ? <UserProfile /> : <LoginButton />}
</header>
);
};
With Custom Parameters
import { useIsAuthenticated } from "@refinedev/core";
const { data } = useIsAuthenticated({
params: {
resource: "posts",
action: "edit",
},
});
Disable Auto-Check
import { useIsAuthenticated } from "@refinedev/core";
import { useState } from "react";
const ManualAuthCheck = () => {
const [checkAuth, setCheckAuth] = useState(false);
const { data, refetch } = useIsAuthenticated({
queryOptions: {
enabled: checkAuth,
},
});
return (
<div>
<button onClick={() => refetch()}>Check Authentication</button>
{data?.authenticated ? "Authenticated" : "Not authenticated"}
</div>
);
};
In a Canvas Application
import { useIsAuthenticated } from "@refinedev/core";
const CanvasHeader = () => {
const { data } = useIsAuthenticated();
const isAuthenticated = data?.authenticated;
return (
<header>
<nav>
<Link to="/">Home</Link>
<Link to="/canvases">Canvases</Link>
</nav>
{isAuthenticated ? (
<LogoutButton />
) : (
<LoginButton />
)}
</header>
);
};