Skip To Main Content

useAuth

useAuth is a React hook that facilitates authentication from your WordPress site.

Configuration

Below is the config object for useAuth defined as a TypeScript type:

type UseAuthOptions = {
  /**
   * Default is "redirect". Learn more about these two strategies
   * @link https://faustjs.org/docs/auth#strategies
   */
  strategy?: 'redirect' | 'local';

  /**
   * The login page Uri. Only applicable/required when strategy is "local".
   */
  loginPageUri?: string;

  /**
   * If useAuth should automatically redirect to the login page
   * if there is no authenticated user.
   */
  shouldRedirect?: boolean;

  /**
   * Used to skip the invocation of the hook. Good for if you 
   * want to call the hook conditionally.
   */
  skip?: boolean;
};
Code language: TypeScript (typescript)

Additionally, the useAuth exports defined as a TypeScript type:

type UseAuth = {
  /**
   * A way to determine if a user is authenticated or not. The value is `null` by default, and then changes to a boolean once the state is determined.
   */
  isAuthenticated: boolean | null;

  /**
   * A boolean to determine if the useAuth exports are ready to be used.
   */
  isReady: boolean;

  /**
   * The url of the login page. This may either be a Next.js file based page or
   * the login page on the WordPress backend based on your strategy.
   */
  loginUrl: string | null;

  /**
   * A callable function to login a user from your Faust app. Accepts a parameter of either username/email, password, and an optional url to redirect the user to after a successful login.
   */
  login: (
    usernameEmail: string,
    password: string,
    redirectUrl?: string,
  ) => void;

  /**
   * A callable function to logout a user from your Faust app. Accepts an optional uri parameter to redirect after logout.
   */
  logout: (redirectUrl?: string) => void;
  
   /**
   * Exposes viewer options to the toolbar if the user is authenticated.
   */
  viewer: = {
    name?: string;
    username?: string;
    capabilities?: string[];
    databaseId?: number;
    description?: string;
    email?: string;
    firstName?: string;
    id?: number;
    lastName?: string;
    nickname?: string;
    locale?: string;
    registeredDate?: string;
    slug?: string;
    templates?: string[];
    uri?: string;
    url?: string;
    userId?: number;
  } | null;
};
Code language: TypeScript (typescript)

Usage

Below is a full example of login/logout and showing/hiding authenticated content. This below example uses the “redirect” strategy:

import { gql, useQuery } from '@apollo/client';
import { getApolloAuthClient, useAuth } from '@faustwp/core';
import { useLogout } from '@faustwp/core';

function AuthenticatedView() {
  const client = getApolloAuthClient();
  const { logout } = useLogout();

  const { data, loading } = useQuery(
    gql`
      {
        viewer {
          posts {
            nodes {
              id
              title
            }
          }
          name
        }
      }
    `,
    { client },
  );

  if (loading) {
    return <>Loading...</>;
  }

  return (
    <>
      <p>Welcome {data?.viewer?.name}!</p>

      <p>My posts</p>

      <ul>
        {data?.viewer?.posts?.nodes.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>

      <button onClick={() => logout()}>Logout</button>
    </>
  );
}

export default function Page(props) {
  const { isAuthenticated, isReady, loginUrl } = useAuth({
    strategy: 'redirect',
    shouldRedirect: false,
  });

  if (!isReady) {
    return <>Loading...</>;
  }

  if (isAuthenticated === true) {
    return <AuthenticatedView />;
  }

  return (
    <>
      <p>Welcome!</p>
      <a href={loginUrl}>Login</a>
    </>
  );
}
Code language: JavaScript (javascript)