Learn how to add authentication with Next.js. The guide covers custom React Hooks, protecting routes and redirecting on the server, and includes a variety of examples.
Authentication verifies who a user is, while authorization controls what a user can access. Next.js supports multiple patterns for authentication, each designed for different use cases. This guide will allow you to choose your adventure based on your constraints.
The first step to identifying which authentication pattern you need is understanding the data-fetching strategy you want. We can then determine which authentication providers support this strategy. There are two main strategies:
Next.js automatically determines that a page is static if there are no blocking data requirements. This means the absence of getServerSideProps
and getInitialProps
in the page. Instead, your page can render a loading state from the server, followed by fetching the user client-side.
One advantage of this pattern is it allows pages to be served from a global CDN and preloaded using <Link />
. Depending on the size of your application, React hydration could take some time. If you serve a loading shell from the server, this allows React to hydrate while you’re fetching user data. In practice, this results in a faster TTI (Time to Interactive).
Let’s look at an example for a profile page. This will initially render a loading skeleton. Once the request for a user has finished, it will show the user’s name.
export default Profile = () => {
// Fetch the user client-side
const { user } = useUser({ redirectTo: '/login' });
// Server-render loading skeleton
if (!user) {
return <LoadingSkeleton />;
}
// Once the user request finishes, show the user's name
return <p>{user.name}</p>;
};
#next #react #security #javascript #web-development