Components
useAuthenticate()
The useAuthenticate() hook automatically redirects unauthenticated users to the sign-in page. If the user is already authenticated, this hook does nothing and allows the user to view the content normally.
This is a hook alternative to the <RedirectToSignIn /> component, useful for redirecting users programmatically.
Usage
import { useAuthenticate } from "better-auth-ui";
export default function ProtectedPage() {
// Will redirect to sign-in if user is not authenticated
useAuthenticate();
return <div>Protected content visible only to authenticated users</div>;
}Options
The hook accepts an options object with the following properties:
interface AuthenticateOptions {
authView?: "signIn" | "signUp"; // Default: "signIn"
enabled?: boolean; // Default: true
}authView: The authentication view to redirect to. Can be either "signIn" or "signUp".enabled: Whether the authentication check is enabled. When set tofalse, no redirection will occur.
Example with Options
import { useAuthenticate } from "better-auth-ui";
export default function ProtectedSignUpPage() {
// Will redirect to sign-up instead of sign-in if user is not authenticated
useAuthenticate({
authView: "signUp",
});
return <div>Protected content</div>;
}Disabling the Redirect
You can conditionally disable the redirection with the enabled option:
import { useAuthenticate } from "better-auth-ui";
export default function ConditionalProtectedPage({
isProtected,
}: {
isProtected: boolean;
}) {
// Only redirect if isProtected is true
useAuthenticate({
enabled: isProtected,
});
return <div>This content may or may not be protected</div>;
}