Protect Frontend
We now need to consider the UI elements in our application and determine access control based on user authentication status. Specifically, we should identify which elements should be exclusive to logged-in users. Additionally, we may need to decide if entire pages should be accessible only after user authentication.
To manage content visibility, we can employ two strategies: Conditional Rendering and Early Return Statements. These methods help in selectively displaying UI components and are effective for securing content based on the user's login status.
Take a look at the example implementation (opens in a new tab) on GitHub. Each step in this chapter is stored in a single commit.
Conditional Rendering: Make UI Elements only accessible for logged-in users
In our example we want only logged-in users to have access to the add Place
button. We can use the useSession hook to evaluate if a user is logged in
and use this information for conditional rendering:
Import useSession hook
import { useSession } from "next-auth/react";
Destructure the session from the useSession hook
const { data: session} = useSession();
Render any UI Element conditionally
{
session && (
<Link href="/create" passHref>
<FixedLink>Add Place</FixedLink>
</Link>
);
}
Early Return: Make a page only accessible for logged-in users
import useSession hook
import { useSession } from "next-auth/react";
Destructure the status
from the useSession hook
In this example we destructure the status
from the useSession hook. This variable will be one of these three values: loading
, authenticated
, or unauthenticated
.
const { status } = useSession();
Before the return statement of the page we use an early return if the status of the session is not authenticated
if (status !== "authenticated") {
return <h2>Access denied!</h2>;
}
return // <...pagecontent...>