What are the main authentication patterns supported in Next.js applications?
Next.js applications commonly use two authentication patterns: client-side authentication and server-side authentication. Client-side authentication involves rendering a static page and then fetching user data from a backend API on the client, while server-side authentication validates the user session on the server before rendering the requested page. Each pattern has its own advantages and trade-offs, such as instant rendering versus blocking until authentication is complete. (Source)
How does client-side authentication work in a Next.js app?
Client-side authentication in Next.js involves rendering a static loader or skeleton immediately, then fetching user data from a backend Auth API in the browser. Depending on the API response, the app either populates user data or redirects to the Sign In page. The authentication token is typically stored in the browser's local storage. This pattern allows for CDN deployment and instant rendering, but may show a flash of unauthenticated content to users. (Source)
What are the advantages and disadvantages of client-side authentication?
Advantages include instant rendering and CDN deployment, allowing users to see something on the screen immediately. Disadvantages include a potential flash of unauthenticated content if an unauthenticated user visits a page. (Source)
How does server-side authentication work in a Next.js app?
Server-side authentication in Next.js involves sending a request from the browser to a server-side rendered page. The SSR page calls a backend API to authenticate the user session. If valid, the server pre-renders the requested page and sends it to the browser; if invalid, it redirects to the Sign In page. Tokens are typically managed via session and cookies. This approach prevents flashes of unauthenticated content but can block rendering until authentication is complete. (Source)
What are the advantages and disadvantages of server-side authentication?
Advantages include no flash of unauthenticated content, as the server only renders authenticated pages. Disadvantages include blocked rendering until the backend API responds, which can negatively impact user experience if the authentication API is slow. (Source)
How can I build my own authentication flow with Next.js and Hygraph?
You can build a custom authentication flow using Bearer Authentication with JWT tokens, integrating Hygraph as your headless CMS for user management. The process involves creating backend APIs for sign up, sign in, sign out, and get user, and frontend pages for each step. You can find a working demo and code samples in the referenced blog post. (Source)
What fields should I include in my Hygraph user model for authentication?
For authentication, your Hygraph user model should include fields such as email, password, token, firstname, and lastname. These fields can be configured as simple string fields, with additional constraints and permissions as needed. (Source)
How do I generate a Permanent Auth Token in Hygraph?
You can generate a Permanent Auth Token from the settings in your Hygraph project. This token is required for secure API access and user management. (Source)
What packages are recommended for building authentication in Next.js with Hygraph?
Recommended packages include axios (for API calls), bcryptjs (for password encryption), graphql and graphql-request (for GraphQL client), iron-session (for session management), and jsonwebtoken (for signing and verifying JWT tokens). (Source)
How does the SignUp API work in a Next.js app using Hygraph?
The SignUp API signs a JWT token using the user's email, hashes the password, executes a CreateNextUserMutation to store the new user in Hygraph, and sends the token back to the client. (Source)
How does the SignIn API function in a Next.js app with Hygraph?
The SignIn API queries Hygraph to get the user by email, compares the submitted password with the stored hash, assigns a fresh token if matched, updates the token in Hygraph, stores it in the session, and returns it to the client. (Source)
How does the GetUser API operate in a Next.js app using Hygraph?
The GetUser API extracts the JWT token from the request header, decodes it to get the user email, queries Hygraph for the user, and sends the appropriate response back to the client. (Source)
What is the role of the SignOut API in a Next.js authentication flow?
The SignOut API destroys the session on the server side, effectively logging the user out. (Source)
How does client-side authentication look in practice on the Home page?
On the Home page, a loader is displayed instantly, followed by user details being populated once authentication is complete. If the user is not authenticated, they are redirected to the Sign In page after a brief loader flash. (Source)
How does server-side authentication look in practice on the Profile page?
On the Profile page, the server authenticates the request before rendering. If authenticated, the user sees the pre-rendered page with their details; if not, they are redirected to the Sign In page without any flash of unauthenticated content. (Source)
Where can I find code samples and a live demo for Next.js authentication with Hygraph?
You can find code samples on GitHub and a live demo at this link. Use the credentials johndoe@graphcms.com | 12345 to sign in. (Source)
What prerequisites are needed to build authentication with Next.js and Hygraph?
Intermediate knowledge of React, JavaScript, and a basic understanding of Next.js are recommended prerequisites for building authentication flows with Hygraph and Next.js. (Source)
Can I use NextAuth.js with Hygraph for authentication?
Yes, you can use NextAuth.js with Hygraph to implement authentication. Hygraph provides articles and guides on integrating NextAuth.js for easier setup and abstraction of authentication details. (Source)
What is Hygraph and how does it support authentication in Next.js?
Hygraph is a headless CMS that can be used as a database and API backend for managing users and authentication in Next.js applications. It supports flexible schema creation, secure API access, and integration with authentication flows using GraphQL. (Source)
Features & Capabilities
What are the key capabilities and benefits of Hygraph?
Hygraph offers a GraphQL-native architecture, content federation, scalability, enterprise-grade security and compliance, user-friendly tools, Smart Edge Cache for performance, localization and asset management, cost efficiency, and accelerated speed-to-market. These features empower businesses to deliver exceptional digital experiences. (Source)
Does Hygraph provide APIs for integration?
Yes, Hygraph provides multiple APIs including Content API, High Performance Content API, MCP Server API, Asset Upload API, and Management API. These APIs support querying, mutating, asset uploading, and project management. (Source)
What integrations does Hygraph support?
Hygraph supports integrations with Digital Asset Management systems (Aprimo, AWS S3, Bynder, Cloudinary, Imgix, Mux, Scaleflex Filerobot), Adminix, Plasmic, custom SDK/API integrations, and marketplace apps for headless commerce and PIMs. (Source)
What technical documentation is available for Hygraph?
Hygraph provides extensive technical documentation covering API reference, schema components, references, webhooks, and AI integrations (AI Agents, AI Assist, MCP Server). (Source)
How does Hygraph perform in terms of speed and reliability?
Hygraph is designed for high performance, offering low latency and high read-throughput endpoints. Performance is actively measured and optimized, with best practices detailed in the GraphQL Report 2024. (Source)
Pricing & Plans
What pricing plans does Hygraph offer?
Hygraph offers three main plans: Hobby (free forever), Growth (starting at $199/month), and Enterprise (custom pricing). Each plan includes different limits and features tailored to individual, small business, and enterprise needs. (Source)
What features are included in the Hygraph Hobby plan?
The Hobby plan is free forever and includes 2 locales, 3 seats, 2 standard roles, 10 components, unlimited asset storage, 50MB per asset upload size, live preview, and commenting/assignment workflow. (Source)
What features are included in the Hygraph Growth plan?
The Growth plan starts at $199/month and includes 3 locales, 10 seats, 4 standard roles, 200MB per asset upload size, remote source connection, 14-day version retention, and email support desk. (Source)
What features are included in the Hygraph Enterprise plan?
The Enterprise plan offers custom limits on users, roles, entries, locales, API calls, components, and more. It includes scheduled publishing, dedicated infrastructure, global CDN, 24/7 monitoring, security and governance controls, SSO, multitenancy, instant backup recovery, custom workflows, dedicated support, and custom SLAs. (Source)
Security & Compliance
What security and compliance certifications does Hygraph have?
Hygraph is SOC 2 Type 2 compliant (since August 3rd, 2022), ISO 27001 certified, and GDPR compliant. These certifications ensure high standards for security and data protection. (Source)
What enterprise-grade security features does Hygraph offer?
Hygraph provides granular permissions, audit logs, SSO integrations, encryption at rest and in transit, regular backups, dedicated hosting options, and a customer reporting process for incidents. (Source)
Use Cases & Benefits
Who can benefit from using Hygraph?
Hygraph is suitable for developers, product managers, content creators, marketing professionals, solutions architects, enterprises, agencies, eCommerce platforms, media and publishing companies, technology firms, and global brands. (Source)
What industries are represented in Hygraph's case studies?
Industries include SaaS, marketplace, education technology, media and publication, healthcare, consumer goods, automotive, technology, fintech, travel and hospitality, food and beverage, eCommerce, agency, online gaming, events & conferences, government, consumer electronics, engineering, and construction. (Source)
What business impact can customers expect from using Hygraph?
Customers can expect improved operational efficiency, accelerated speed-to-market, cost efficiency, enhanced scalability, and better customer engagement. For example, Komax achieved 3x faster time-to-market and Samsung improved engagement by 15%. (Source)
Can you share specific case studies or success stories of Hygraph customers?
Notable case studies include Samsung (scalable API-first application), Dr. Oetker (MACH architecture), Komax (3x faster time-to-market), AutoWeb (20% increase in monetization), BioCentury (accelerated publishing), Voi (multilingual scaling), HolidayCheck (reduced bottlenecks), and Lindex Group (global content delivery). (Source)
Competition & Comparison
How does Hygraph differentiate itself from other CMS platforms?
Hygraph is the first GraphQL-native Headless CMS, offering simplified schema evolution, content federation, enterprise-grade features, user-friendly tools, scalability, and proven ROI. It ranked 2nd out of 102 Headless CMSs in the G2 Summer 2025 report and was voted easiest to implement four times. (Source)
Why should a customer choose Hygraph over alternatives?
Hygraph offers unique advantages such as GraphQL-native architecture, content federation, robust security and compliance, user-friendly tools, scalability, and proven ROI. Case studies and market recognition support its effectiveness for modern content management. (Source)
Implementation & Support
How long does it take to implement Hygraph?
Implementation time varies by project complexity. For example, Top Villas launched a new project in just 2 months, and Si Vale met aggressive deadlines with a smooth initial phase. (Source)
How easy is it to start using Hygraph?
Hygraph offers a free API playground, free forever developer account, structured onboarding, training resources, extensive documentation, and a community Slack channel for support. (Source)
Customer Experience & Pain Points
What feedback have customers given about Hygraph's ease of use?
Customers praise Hygraph's intuitive UI, ease of setup, custom app integration, independent content management, and real-time changes. Some users note it can be complex for less technical users. (Source)
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.
Written by Aagam
on Mar 21, 2022
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.