What are the main authentication patterns available in Next.js applications?
Next.js applications commonly use two authentication patterns: client-side authentication and server-side authentication. Client-side authentication handles user verification in the browser after an initial static page render, while server-side authentication verifies the user on the server before rendering the page. Each approach has distinct advantages and trade-offs. Note: Choosing between these patterns depends on your data fetching strategy and user experience requirements.
How does client-side authentication work in a Next.js app using Hygraph?
In client-side authentication, the browser requests a static page, which renders immediately. The app then fetches user data from a backend Auth API (such as one built with Hygraph) and, based on the response, either populates the page or redirects to the sign-in page. The authentication token is typically stored in the browser's local storage. This approach allows for CDN deployment and instant rendering but may result in a brief flash of unauthenticated content for users who are not signed in. Note: This method is not ideal if you need to avoid any unauthenticated content flashes.
How does server-side authentication work in a Next.js app using Hygraph?
With server-side authentication, the browser requests a page that is rendered on the server. The server verifies the user session by calling a backend API (which can interact with Hygraph), and if valid, pre-renders the page and sends it to the browser. If the session is invalid, the user is redirected to the sign-in page. Tokens are typically managed via sessions and cookies. This approach prevents flashes of unauthenticated content but can block rendering until the backend API responds, potentially impacting user experience if the API is slow. Note: Rendering delays are a key limitation of this pattern.
What are the main steps to implement authentication in a Next.js app with Hygraph?
The main steps include: 1) Setting up a Hygraph project and creating a user model (e.g., NextUser with fields like email, password, token, firstname, lastname); 2) Building backend APIs for sign-up, sign-in, sign-out, and get-user operations; 3) Implementing client-side and server-side authentication flows in Next.js pages; 4) Managing tokens with JWT and sessions; 5) Using libraries such as graphql-request, axios, bcryptjs, jsonwebtoken, and iron-session. Note: Intermediate knowledge of React, JavaScript, and Next.js is required for this implementation.
What are the advantages and disadvantages of client-side vs. server-side authentication in Next.js?
Client-side authentication allows for instant page rendering and CDN deployment but may show a flash of unauthenticated content to users who are not signed in. Server-side authentication prevents this flash by verifying users before rendering, but page rendering is blocked until the backend API responds, which can slow down the user experience if the API is slow. Note: The choice depends on your application's user experience and security requirements.
How do you manage user sessions and tokens in a Next.js app with Hygraph?
User sessions and tokens are managed using JWT for authentication and libraries like iron-session for session management. Tokens are generated during sign-up and sign-in, stored in the Hygraph database, and sent to the client. For client-side authentication, tokens are stored in local storage; for server-side authentication, tokens are stored in sessions and cookies. Note: Proper management of token expiration and secure storage is essential for security.
What APIs need to be implemented for authentication in a Next.js app with Hygraph?
The required APIs are: SignUp (creates a user and returns a JWT token), SignIn (verifies credentials, issues a new token, and manages sessions), GetUser (verifies the token and fetches user details), and SignOut (destroys the session). These APIs interact with Hygraph using GraphQL queries and mutations. Note: Each API must handle errors and edge cases, such as invalid credentials or expired tokens.
What are the prerequisites for building authentication with Next.js and Hygraph?
Intermediate knowledge of React, JavaScript, and basic understanding of Next.js is required. You should also be familiar with GraphQL, JWT, and session management concepts. Setting up environment variables and using libraries such as graphql-request, axios, bcryptjs, jsonwebtoken, and iron-session is necessary. Note: Without these prerequisites, implementation may be challenging.
Are there any ready-made libraries for authentication with Next.js and Hygraph?
Yes, you can use libraries like NextAuth.js to simplify authentication in Next.js applications. NextAuth.js abstracts away many implementation details and can be integrated with Hygraph for user management. For more information, see the articles on Next.js Authentication with NextAuth.js and Hygraph and Working With NextAuth and User Generated Content. Note: Using a library may limit customization compared to a fully custom implementation.
Hygraph Platform Features & Security
What security and compliance certifications does Hygraph hold?
Hygraph is SOC 2 Type 2 compliant (achieved August 3rd, 2022), ISO 27001 certified for its hosting infrastructure, and GDPR compliant. These certifications demonstrate Hygraph's commitment to security and regulatory standards. Note: For more details, visit Hygraph's Secure Features page.
What integrations does Hygraph support for authentication and content management?
Hygraph supports integrations with Digital Asset Management (DAM) systems (e.g., Aprimo, AWS S3, Bynder, Cloudinary, Imgix, Mux, Scaleflex Filerobot), hosting and deployment platforms (Netlify, Vercel), Product Information Management (Akeneo), commerce solutions (BigCommerce), and translation/localization tools (EasyTranslate). For a full list, visit the Hygraph Marketplace. Note: Integration capabilities may require additional configuration depending on your use case.
What technical documentation is available for implementing authentication with Hygraph?
Hygraph provides comprehensive technical documentation, including API references, guides for schema components and references, integration guides (e.g., Mux, Akeneo, Auth0), and AI feature documentation. For authentication-specific use cases, see the API Reference and related blog tutorials. Note: Documentation for Hygraph Classic is also available for legacy projects.
Implementation & Use Cases
How long does it take to implement authentication with Hygraph in a Next.js app?
Implementation time varies by project complexity. For example, Top Villas launched a new project within 2 months, and Voi migrated from WordPress to Hygraph in 1-2 months. Hygraph provides starter projects, onboarding guides, and community support to accelerate setup. Note: Custom authentication flows may require additional development time.
What are the main limitations or edge cases when using Hygraph for authentication in Next.js?
Client-side authentication can result in a flash of unauthenticated content, while server-side authentication may block rendering if the backend API is slow. Custom implementations require careful management of tokens, sessions, and error handling. Detailed limitations for Hygraph's authentication use cases are not publicly documented; ask sales or consult the documentation for specifics.
We will break down the difference between server-side and client-side authentication & demo how each of these look in practice in a simple Next.js application.
Last updated by Aagam
on Jan 21, 2026
Originally written by Aagam
Next.js is a hybrid framework on top of React, which enables static and server-side rendering. It comes with a bunch of awesome features like file system routing, typescript support, image optimization, code-splitting & bundling, etc, which are pretty useful for any developer. All in all, it is an impressive production framework for React.
When building any application, we often need to handle authentication before moving to the core of the app. In fact for major web apps, authentication is absolutely necessary. In this article, we’ll explore in-depth, with the help of a demo, authentication patterns for a Next.js app. There are two main patterns to authenticate users in Next.js and which one to use will depend on your data fetching strategy.
In this pattern, the request is sent from the browser to a static page on our Next.js App, our Next app immediately renders a static-loader/loading-skeleton. After that, on the client-side (i.e the browser), we fetch the user data by calling our Backend Auth API, depending on the response from the API, we either populate the data or redirect the user to the Sign In page. The illustration below will help you understand the flow better.
In this strategy, you’ll need to store the authentication token on the client-side somewhere, for example, the browser’s local storage.
Advantages of this pattern include that the app can be deployed on a Content Delivery Network (CDN) and that the user will immediately see something rendered on the screen. The rendering will not be blocked.
One disadvantage of this pattern is that if an unauthenticated user tries to visit a page, there will be a flash of unauthenticated content.
In this pattern, the request is sent from the browser to a server-side page on our Next.js App. The SSR page calls a backend API to authenticate the user session, if the session is valid the server pre-renders the requested page on the backend and sends it to the browser, if the session is invalid, the server redirects to the Sign In page.
In this strategy, you can use session and cookie to handle the token for authentication.
One advantage of this pattern is that there will be no flash of unauthenticated content.
One disadvantage is that the rendering will be blocked until there is a response from the backend API (not your Next.js SSR page, your backend Auth API). So if the authentication API is slow, it will be bad for user experience.
Building an application would be perfect to understand these patterns better. We’ll build an application that uses Bearer Authentication with jwt-tokens to authenticate a user from scratch. This kind of auth setup is common and used by many production projects. If you’ve used it in any other project and are wondering how to integrate the same with Next.js, this article is the right place to be. By the end, you’ll have a full-fledged Next.js App with authentication for both static and server-rendered pages. This app can even act as a decent base for your future projects.
Also, intermediate knowledge of React, Javascript, and a basic understanding of Next.js is a prerequisite to building this app.
A quick note: if you’re looking for something easier, like a library that abstracts away many details, does the heavy lifting for you, I’d recommend checking out our articles on implementing Authentication with NextAuth.js.
Hygraph Headless CMS: We’ll need a DB and a headless CMS to manage our users, we’ll use Hygraph for the same.
Next.js App
Backend APIs: We’ll build 4 APIs, we’ll also learn how to interact with Hygraph in the process.
Sign Up API
Sign In API
Sign Out API
Get User API
Pages
Sign Up Page
Sign In Page
Home Page - This page will use the client-side authentication pattern.
Profile Page - This page will use the server-side authentication pattern.
If you want to take a look at the final code, you can find the code here. You can also find a working live demo of what we’ll build here. Use the credentials: johndoe@graphcms.com | 12345 to Sign in.
With the brief given, let's jump in, and get our hands dirty!
Setting up Hygraph
Login to your Hygraph account and if you don't have one, visit Hygraph and create one.
Create a new project let’s name it next-auth-patterns and add a new model NextUser
Let's add a few fields to our model.
email
password
token
firstname
lastname
We’ll keep them as simple string fields, you can of course play with different constraints and permissions but that is beyond the scope of this tutorial. After completing the steps above your model should look something like this:
You’ll also need a Permanent Auth Token which you can generate from the settings.
Setting up our Next.js App
I’ll be using yarn as my package manager, feel free to use npm if you’d like.
Let’s create a Next.js App with yarn create next-app next-auth-demo
Now, add all packages which we will use along the way:
axios
bcryptjs
graphql
graphql-request
iron-session
jsonwebtoken
Regarding all these modules, we’ll use the graphql-request as our graphql client, axios will help us with making the API calls. We’ll use jsonwebtoken to sign and verify the jwt-tokens for our users, bcryptjs will encrypt the passwords so we don’t have to store them in plain text in the database, and lastly iron-session will help us with session management for server side authentication.
In your .env.local add these variables. There are some env’s which will be specific for you, so make sure you fill all environment variables properly.
For a Javascript Dev, these pieces of code should be pretty straight forward.
Frontend Pages
I’ll be using tailwind-css to make the frontend look a bit better, so don’t worry about the classes in my jsx templates, you can use Tailwind with next.js or any other css-framework if you wish to!
Let’s add these common frontend pages/components that are straightforward.
const{ authenticated, user }=awaitgetAuthenticatedUser();
if(!authenticated){
Router.push(APP_ROUTES.SIGN_IN);
return;
}
setUser(user);
setAutenticated(authenticated);
}
getUserDetails();
},[]);
return{ user, authenticated };
}
Here we are implementing the client side authentication flow which goes something like this
Browser requests for the index page.
Our Next App immediately returns a Static Page which renders a loading state.
The API call to the backend API happens from the useUser hook from the client (browser).
The hook receives a response and accordingly action is taken.
The useUser hook is common and can be used anywhere in your app where client side authentication is required.
Once you’ve built this, when you visit the Home Page at / path
You’ll see the layout with a loader displayed instantly and then the details being populated.
If you logout and then try to visit the / path then you’ll still see the loader for a fraction of a second and then you’ll be redirected to signin. That is what was being referred to earlier as a flash of unauthenticated content.
Here we’re implementing the server-side authentication flow which goes something like this:
Browser requests for the profile page.
Our Next app SSR Profile Page authenticates that request on the server itself
In getServerSideProps which runs on the server side in Next.js
We extract the token from the user session.
We authenticate if the token is a valid one.
If there is no token / token is invalid, we send back a redirect to signin page.
If the token from the session is valid, then only the jsx for the page will be pre-rendered on the server and the requested page will be sent to the browser.
Once you’ve built this, when you visit the Profile Page at /profile path ,
The rendering will not be instant like it was in the client side authentication, the page render will be blocked for some time which depends on the speed of your backend API.
If you are signed in, you won’t see any loader, you’ll directly get the pre-rendered page with all the data populated.
If you are signed out, you won’t get a flash of unauthenticated content, you’ll see the signin page directly.
You can try this exercise out with the live demo too.
Thanks for reading and making it till here! We hope this article helps you out in your project.
Blog Author
Aagam Vadecha
As a Software Engineer, my daily routine revolves around writing scalable applications with clean code & maintaining them. In my spare time, I love to explore software architecture patterns, write tech articles & watch thrillers!
Share with others
Sign up for our newsletter!
Be the first to know about releases and industry news and insights.
We will break down the difference between server-side and client-side authentication & demo how each of these look in practice in a simple Next.js application.
Last updated by Aagam
on Jan 21, 2026
Originally written by Aagam
Next.js is a hybrid framework on top of React, which enables static and server-side rendering. It comes with a bunch of awesome features like file system routing, typescript support, image optimization, code-splitting & bundling, etc, which are pretty useful for any developer. All in all, it is an impressive production framework for React.
When building any application, we often need to handle authentication before moving to the core of the app. In fact for major web apps, authentication is absolutely necessary. In this article, we’ll explore in-depth, with the help of a demo, authentication patterns for a Next.js app. There are two main patterns to authenticate users in Next.js and which one to use will depend on your data fetching strategy.
In this pattern, the request is sent from the browser to a static page on our Next.js App, our Next app immediately renders a static-loader/loading-skeleton. After that, on the client-side (i.e the browser), we fetch the user data by calling our Backend Auth API, depending on the response from the API, we either populate the data or redirect the user to the Sign In page. The illustration below will help you understand the flow better.
In this strategy, you’ll need to store the authentication token on the client-side somewhere, for example, the browser’s local storage.
Advantages of this pattern include that the app can be deployed on a Content Delivery Network (CDN) and that the user will immediately see something rendered on the screen. The rendering will not be blocked.
One disadvantage of this pattern is that if an unauthenticated user tries to visit a page, there will be a flash of unauthenticated content.
In this pattern, the request is sent from the browser to a server-side page on our Next.js App. The SSR page calls a backend API to authenticate the user session, if the session is valid the server pre-renders the requested page on the backend and sends it to the browser, if the session is invalid, the server redirects to the Sign In page.
In this strategy, you can use session and cookie to handle the token for authentication.
One advantage of this pattern is that there will be no flash of unauthenticated content.
One disadvantage is that the rendering will be blocked until there is a response from the backend API (not your Next.js SSR page, your backend Auth API). So if the authentication API is slow, it will be bad for user experience.
Building an application would be perfect to understand these patterns better. We’ll build an application that uses Bearer Authentication with jwt-tokens to authenticate a user from scratch. This kind of auth setup is common and used by many production projects. If you’ve used it in any other project and are wondering how to integrate the same with Next.js, this article is the right place to be. By the end, you’ll have a full-fledged Next.js App with authentication for both static and server-rendered pages. This app can even act as a decent base for your future projects.
Also, intermediate knowledge of React, Javascript, and a basic understanding of Next.js is a prerequisite to building this app.
A quick note: if you’re looking for something easier, like a library that abstracts away many details, does the heavy lifting for you, I’d recommend checking out our articles on implementing Authentication with NextAuth.js.
Hygraph Headless CMS: We’ll need a DB and a headless CMS to manage our users, we’ll use Hygraph for the same.
Next.js App
Backend APIs: We’ll build 4 APIs, we’ll also learn how to interact with Hygraph in the process.
Sign Up API
Sign In API
Sign Out API
Get User API
Pages
Sign Up Page
Sign In Page
Home Page - This page will use the client-side authentication pattern.
Profile Page - This page will use the server-side authentication pattern.
If you want to take a look at the final code, you can find the code here. You can also find a working live demo of what we’ll build here. Use the credentials: johndoe@graphcms.com | 12345 to Sign in.
With the brief given, let's jump in, and get our hands dirty!
Setting up Hygraph
Login to your Hygraph account and if you don't have one, visit Hygraph and create one.
Create a new project let’s name it next-auth-patterns and add a new model NextUser
Let's add a few fields to our model.
email
password
token
firstname
lastname
We’ll keep them as simple string fields, you can of course play with different constraints and permissions but that is beyond the scope of this tutorial. After completing the steps above your model should look something like this:
You’ll also need a Permanent Auth Token which you can generate from the settings.
Setting up our Next.js App
I’ll be using yarn as my package manager, feel free to use npm if you’d like.
Let’s create a Next.js App with yarn create next-app next-auth-demo
Now, add all packages which we will use along the way:
axios
bcryptjs
graphql
graphql-request
iron-session
jsonwebtoken
Regarding all these modules, we’ll use the graphql-request as our graphql client, axios will help us with making the API calls. We’ll use jsonwebtoken to sign and verify the jwt-tokens for our users, bcryptjs will encrypt the passwords so we don’t have to store them in plain text in the database, and lastly iron-session will help us with session management for server side authentication.
In your .env.local add these variables. There are some env’s which will be specific for you, so make sure you fill all environment variables properly.
For a Javascript Dev, these pieces of code should be pretty straight forward.
Frontend Pages
I’ll be using tailwind-css to make the frontend look a bit better, so don’t worry about the classes in my jsx templates, you can use Tailwind with next.js or any other css-framework if you wish to!
Let’s add these common frontend pages/components that are straightforward.
const{ authenticated, user }=awaitgetAuthenticatedUser();
if(!authenticated){
Router.push(APP_ROUTES.SIGN_IN);
return;
}
setUser(user);
setAutenticated(authenticated);
}
getUserDetails();
},[]);
return{ user, authenticated };
}
Here we are implementing the client side authentication flow which goes something like this
Browser requests for the index page.
Our Next App immediately returns a Static Page which renders a loading state.
The API call to the backend API happens from the useUser hook from the client (browser).
The hook receives a response and accordingly action is taken.
The useUser hook is common and can be used anywhere in your app where client side authentication is required.
Once you’ve built this, when you visit the Home Page at / path
You’ll see the layout with a loader displayed instantly and then the details being populated.
If you logout and then try to visit the / path then you’ll still see the loader for a fraction of a second and then you’ll be redirected to signin. That is what was being referred to earlier as a flash of unauthenticated content.
Here we’re implementing the server-side authentication flow which goes something like this:
Browser requests for the profile page.
Our Next app SSR Profile Page authenticates that request on the server itself
In getServerSideProps which runs on the server side in Next.js
We extract the token from the user session.
We authenticate if the token is a valid one.
If there is no token / token is invalid, we send back a redirect to signin page.
If the token from the session is valid, then only the jsx for the page will be pre-rendered on the server and the requested page will be sent to the browser.
Once you’ve built this, when you visit the Profile Page at /profile path ,
The rendering will not be instant like it was in the client side authentication, the page render will be blocked for some time which depends on the speed of your backend API.
If you are signed in, you won’t see any loader, you’ll directly get the pre-rendered page with all the data populated.
If you are signed out, you won’t get a flash of unauthenticated content, you’ll see the signin page directly.
You can try this exercise out with the live demo too.
Thanks for reading and making it till here! We hope this article helps you out in your project.
Blog Author
Aagam Vadecha
As a Software Engineer, my daily routine revolves around writing scalable applications with clean code & maintaining them. In my spare time, I love to explore software architecture patterns, write tech articles & watch thrillers!
Share with others
Sign up for our newsletter!
Be the first to know about releases and industry news and insights.