Auth
Understanding authentication is crucial for protecting your application's data. This page will guide you through implementing features from the Faust.js toolkit into your Next.js app.
Before starting, it helps to break down the process into three concepts:
-
Authentication: Verifies if the user is who they say they are. It requires the user to prove their identity with something they have, such as a username and password.
-
Session Management: Tracks the user's auth state across requests.
-
Authorization: Decides what routes and data the user can access.
This diagram shows the authentication flow using the Faust.js toolkit auth feature:
Redirect-based authentication is the default strategy in the Faust.js toolkit. This strategy involves redirecting the user to WordPress to authenticate. Once the user has shown authentication, the user redirects back to the Next.js application with an authorization code, which you can then use to request a refresh and access token, thus completing the login process.
This strategy is excellent for use cases where your authenticated users are admins/editors/etc. and do not necessarily need a “white label” login/register experience. Typically, you would use the redirect strategy if your primary reason for authentication is previewing posts and pages.
In this doc, we will walk through how to add authentication support to your headless WordPress project using Faust.js toolkit.
Steps
1. Basic setup
If you haven't already, follow the Basic Setup steps to get Faust.js set up.
2. Implement auth functionality
You are now ready to implement the auth functionality. Create a /gated/index.js
page in the pages
directory and paste this code block into the file:
import { useAuth, getApolloAuthClient, useLogout } from "@faustwp/core";
import { gql, useQuery } from "@apollo/client";
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>
<button onClick={() => logout("/")}>Logout</button>
<p>My posts</p>
<ul>
{data?.viewer?.posts?.nodes.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</>
);
}
export default function Page() {
const { isAuthenticated, isReady, loginUrl } = useAuth();
if (!isReady) {
return <>Loading...</>;
}
if (isAuthenticated === true) {
return <AuthenticatedView />;
}
return (
<>
<p>Welcome!</p>
<a href={loginUrl}>Login</a>
</>
);
}
In this code block, to check if a user is logged in, we use the useAuth
hook, focusing on its isReady
and isAuthenticated
properties. The isReady
property ensures that the hook is fully set up and ready to determine the user's authentication status. Once isReady
confirms the setup, it returns a boolean, after which isAuthenticated
will also return a boolean value indicating whether the user is logged in.
For authenticated requests, the getApolloAuthClient()
function is used to obtain an Apollo Client instance with the appropriate access token attached. This client can be utilized for making authenticated requests, either directly via client.query
or by passing the client into Apollo's useQuery
hook.
In the AuthenticatedView
component, we use the useQuery
hook along with the authenticated client to fetch data, specifically the user's name and posts. If the data is loading, a loading message is displayed. Once the data is available, the component renders a welcome message, a logout button, and a list of the user's posts.
The main Page
component uses isReady
and isAuthenticated
to manage the user interface. If the authentication state is not ready, it shows a loading state. If the user is authenticated, it renders the AuthenticatedView
component. Otherwise, it presents a login link that directs you to log in from the WordPress admin.
Step 3. Test auth
You are now ready to access the auth page you created. In your terminal start up the dev server by running npm run dev
and visit the http://localhost:3000/gated
route. If the authentication was set up properly, you should be redirected to the WP login screen. Once you login, you should be sent back to the gated page and see the gated content.
Next steps
Here are some things you can do to continue to test and add to your auth strategy with the toolkit:
- You can verify that authentication is working by adding a
console.log()
with the current user's name to check whether they are being authenticated properly. Using the above code example, it would look like this:
import { useAuth, getApolloAuthClient, useLogout } from "@faustwp/core";
import { gql, useQuery } from "@apollo/client";
function AuthenticatedView() {
const client = getApolloAuthClient();
const { logout } = useLogout();
const { data, loading } = useQuery(
gql`
{
viewer {
posts {
nodes {
id
title
}
}
name
}
}
`,
{ client }
);
if (loading) {
return <>Loading...</>;
}
// Console log the current user's name to verify authentication
console.log("Authenticated user's name:", data?.viewer?.name);
// Rest of your component
- Local Based Authentication is the second strategy available in Faust.js. This strategy involves the user initiating a login request from the Next.js application via the
useLogin
hook. Upon successful login,useLogin
returns an authorization code used to request a refresh and access token, thus completing the login process.
This strategy is excellent for use cases where you want to support a more “white label” login/register experience. It routes unauthenticated requests to your specified Next.js login page. In addition, users who wish to log in/register will not have to interact with WordPress or the WordPress backend at all, giving you the flexibility to implement and fine-tune your user flow. If you are interested in using this strategy, please visit this article here on the subject:
https://wpengine.com/builders/authentication-in-faust-js-and-headless-wp/#implementing-local-auth