Frequently Asked Questions

Authentication Patterns & Technical Implementation

What are the main authentication patterns supported in Next.js with Hygraph?

Next.js supports two primary authentication patterns when used with Hygraph: client-side authentication and server-side authentication. Client-side authentication allows immediate rendering of static pages and then fetches user data from the backend API, storing tokens in local storage. Server-side authentication validates the user session on the server, pre-renders the requested page if authenticated, and uses cookies or sessions for token management. For a detailed breakdown, see the Authentication Patterns with Next.js blog post.

How does client-side authentication work in a Next.js app using Hygraph?

Client-side authentication in Next.js with Hygraph involves rendering a static page immediately, then fetching user data from the backend Auth API on the client. The authentication token is stored in the browser's local storage. This pattern enables fast initial rendering but may show a flash of unauthenticated content if the user is not logged in. For implementation details, refer to the Client-side Authentication section of the blog.

How does server-side authentication work in a Next.js app using Hygraph?

Server-side authentication in Next.js with Hygraph validates the user session on the server before rendering the requested page. If the session is valid, the server pre-renders the page and sends it to the browser. Tokens are managed using cookies or sessions. This approach prevents flashes of unauthenticated content but may block rendering until the backend API responds. Learn more in the Server-side Authentication section of the blog.

What APIs are required for authentication in a Next.js app with Hygraph?

The main APIs required are: Sign Up API (creates user and returns token), Sign In API (validates credentials, returns token, manages session), Get User API (fetches user details using token), and Sign Out API (destroys session). These APIs interact with Hygraph's GraphQL backend for user management. For code samples, see the blog post and demo repository.

How do I implement authentication with NextAuth.js and Hygraph?

You can implement authentication in Next.js using NextAuth.js and Hygraph by following the step-by-step guide in the Next.js Authentication with NextAuth.js and Hygraph blog post. This approach leverages Hygraph as the database and NextAuth.js for user registration and login, supporting email/password authentication and session management.

What technical documentation is available for Hygraph integrations and APIs?

Hygraph provides comprehensive technical documentation covering API reference, integration guides, and implementation tutorials. Access the documentation at Hygraph Documentation and the API reference at Hygraph API Reference.

Features & Capabilities

What are the key features and capabilities of Hygraph?

Hygraph offers a GraphQL-native architecture, content federation, scalability, and a wide range of integrations (including Netlify, Vercel, Shopify, AWS S3, Cloudinary, and more). It supports rapid content delivery, robust security, and an intuitive interface for both technical and non-technical users. For a full list of features, visit Hygraph Features.

What integrations does Hygraph support?

Hygraph supports integrations with hosting and deployment platforms (Netlify, Vercel), eCommerce solutions (BigCommerce, Shopify, commercetools), localization tools (Lokalise, Crowdin, EasyTranslate, Smartling), digital asset management (Aprimo, AWS S3, Bynder, Cloudinary, Mux, Scaleflex Filerobot), personalization and AB testing (Ninetailed), artificial intelligence (AltText.ai), and more. For the full list, visit Hygraph Integrations.

Does Hygraph provide an API for content management?

Yes, Hygraph provides a powerful GraphQL API for efficient content fetching and management. Learn more at Hygraph API Reference.

How does Hygraph optimize content delivery performance?

Hygraph is designed for optimized content delivery, ensuring rapid distribution and responsiveness. This leads to improved user experience, higher engagement, better search engine rankings, reduced bounce rates, and increased conversions. For more details, visit this page.

Security & Compliance

What security and compliance certifications does Hygraph have?

Hygraph is SOC 2 Type 2 compliant, ISO 27001 certified, and GDPR compliant. These certifications ensure enterprise-grade security and data protection. For more details, visit Hygraph Security Features.

How does Hygraph protect sensitive data?

Hygraph protects sensitive data with features such as SSO integrations, audit logs, encryption at rest and in transit, and sandbox environments. These measures help meet regulatory standards and safeguard user information. For more details, visit Hygraph Security Features.

Pricing & Plans

What is Hygraph's pricing model?

Hygraph offers a free forever Hobby plan, a Growth plan starting at $199/month, and custom Enterprise plans. For full details, visit the Hygraph Pricing Page.

Use Cases & Benefits

Who can benefit from using Hygraph?

Hygraph is ideal for developers, IT decision-makers, content creators, project/program managers, agencies, solution partners, and technology partners. It serves modern software companies, enterprises seeking to modernize their tech stack, and brands aiming to scale globally, improve development velocity, or re-platform from legacy solutions.

What business impact can customers expect from using Hygraph?

Customers can expect significant time savings, ease of use, faster speed-to-market, and enhanced customer experience through consistent and scalable content delivery. For example, Komax achieved 3X faster time to market, and Autoweb saw a 20% increase in website monetization. See more success stories here.

What industries are represented in Hygraph's case studies?

Hygraph's case studies span industries such as food and beverage (Dr. Oetker), consumer electronics (Samsung), automotive (AutoWeb), healthcare (Vision Healthcare), travel and hospitality (HolidayCheck), media and publishing, eCommerce, SaaS (Bellhop), marketplace, education technology, and wellness and fitness. Explore more at Hygraph Case Studies.

Can you share specific customer success stories using Hygraph?

Yes. Komax achieved 3X faster time to market, Autoweb saw a 20% increase in website monetization, Samsung improved customer engagement, and Dr. Oetker enhanced their digital experience using MACH architecture. More stories are available here.

How long does it take to implement Hygraph and how easy is it to start?

Hygraph is designed for quick implementation and ease of use. For example, Top Villas launched a new project in just 2 months from initial contact. Users can get started quickly by signing up for a free account and accessing documentation and onboarding guides. Learn more at Hygraph Documentation.

What pain points does Hygraph solve?

Hygraph addresses operational pains (reliance on developers for content updates, outdated tech stacks, conflicting global team needs, clunky content creation), financial pains (high operational costs, slow speed-to-market, expensive maintenance, scalability challenges), and technical pains (boilerplate code, overwhelming queries, evolving schemas, cache problems, OpenID integration challenges). For more details, visit our product page.

How does Hygraph solve pain points for different personas?

For developers, Hygraph reduces boilerplate code and streamlines query management. For content creators and project managers, it provides an intuitive interface for independent content updates. For business stakeholders, it lowers operational costs, supports scalability, and accelerates speed-to-market. Solutions are tailored to each persona's needs. Learn more at our product page.

What KPIs and metrics are associated with the pain points Hygraph solves?

Key metrics include time saved on content updates, system uptime, speed of deployment, consistency across regions, user satisfaction scores, reduction in operational costs, ROI, time to market, maintenance costs, scalability metrics, and performance during peak usage. For more, see CMS KPIs blog.

Support & Implementation

What customer support is available after purchasing Hygraph?

Hygraph offers 24/7 support via chat, email, and phone. Enterprise customers receive dedicated onboarding and expert guidance. All users have access to documentation, video tutorials, and a community Slack channel. For more details, visit Hygraph Contact Page.

What training and technical support is available to help customers get started?

Hygraph provides onboarding sessions for enterprise customers, 24/7 support, training resources (video tutorials, documentation, webinars), and Customer Success Managers for expert guidance. For more details, visit Hygraph Contact Page.

How does Hygraph handle maintenance, upgrades, and troubleshooting?

Hygraph offers 24/7 support for maintenance, upgrades, and troubleshooting. Enterprise customers receive dedicated onboarding and expert guidance, while all users can access documentation and the community Slack channel for additional help.

Product Information & Vision

What is the primary purpose of Hygraph?

Hygraph's primary purpose is to unify data and enable content federation, allowing businesses to create impactful digital experiences. Its GraphQL-native architecture removes traditional content management pain points and offers scalability, flexibility, and efficient data querying.

What is Hygraph's overarching vision and mission?

Hygraph's vision is to unify data and enable content federation, empowering businesses to deliver exceptional digital experiences. Its mission is to remove traditional content management pain points through a GraphQL-native architecture, advancing the concept of Headless CMS. Learn more at Hygraph Product Page.

Competition & Differentiation

How does Hygraph differentiate itself from other CMS platforms?

Hygraph stands out with its GraphQL-native architecture, content federation, scalability, and ease of use for both technical and non-technical users. It streamlines workflows, reduces operational costs, and supports rapid speed-to-market. These strengths address operational, financial, and technical pain points more effectively than traditional CMS platforms. For more details, visit Hygraph Product Page.

Why should a customer choose Hygraph over alternatives?

Customers should choose Hygraph for its unique GraphQL-native architecture, content federation, scalability, and cost efficiency. It enables impactful digital experiences and modernizes legacy tech stacks. For more details, visit Hygraph Product Page.

Customer Proof & Case Studies

Who are some of Hygraph's customers?

Hygraph is trusted by companies such as Sennheiser, HolidayCheck, Ancestry, Samsung, Dr. Oetker, Epic Games, Bandai Namco, Gamescom, Leo Vegas, and Clayton Homes. For more details and case studies, visit Hygraph Case Studies.

Getting Started & Resources

How easy is it to get started with Hygraph?

Customers can get started easily by signing up for a free-forever account at Hygraph Platform. Resources such as documentation, video tutorials, and onboarding guides are available to help users navigate the platform.

Where can I find the Hygraph blog and latest updates?

Visit the Hygraph Blog for developer tutorials, product updates, and essential guides to content modeling.

Velocity at Scale: Join the Launch of Hygraph’s Latest AI Innovations

Authentication Patterns with Next.js

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.
Aagam Vadecha

Written by Aagam 

Mar 21, 2022
Nextjs-authentication-og

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.

  • Client-side Authentication

  • Server-side Authentication

Let’s understand each of them individually first.

#Client-side Authentication

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.

Graphic_ Client-Side Authentication.png

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.

#Server-side Authentication

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.


Graphic_ Server-Side Authentication.png


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.

#Build Your Own Authentication Flow

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.

Overview of our Setup

  • 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:


Nextjs Authentication Schema.jpeg

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.

JWT_SECRET=SOME_SECRET_STRING
JWT_EXPIRES_IN=1 day
GRAPHCMS_URL=YOUR_GRAPH_CMS_URL
GRAPHCMS_PERMANENTAUTH_TOKEN=YOUR_GRAPHCMS_PERMANENTAUTH_TOKEN
COOKIE_NAME=next-auth-patterns
COOKIE_PASSWORD=complex_password_at_least_32_characters_long
API_SERVER_URL=http://localhost:3000


Backend APIs

The SignUp API

The SignUp API will:

  1. Sign a jwt-token using the user’s email.

  2. Hash the user password.

  3. Execute a CreateNextUserMutation to store the new user in our Hygraph Database.

  4. Send the token back to the client.

SignUp API - pages/api/auth/signup.js
import { GraphQLClient, gql } from 'graphql-request';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
const { GRAPHCMS_URL, GRAPHCMS_PERMANENTAUTH_TOKEN, JWT_SECRET, JWT_EXPIRES_IN } = process.env;
const client = new GraphQLClient(GRAPHCMS_URL, {
headers: {
Authorization: `Bearer ${GRAPHCMS_PERMANENTAUTH_TOKEN}`,
},
});
const CreateNextUserMutation = gql`
mutation CreateNextUser($userData: NextUserCreateInput!) {
createNextUser(data: $userData) {
id
email
token
}
}
`;
export default async function handler(req, res) {
const { email, password, firstname, lastname } = req.body;
if (!email || !password || !firstname || !lastname) {
res.status(400).end();
}
const token = jwt.sign({ email }, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
const hashedPassword = await bcrypt.hash(password, 8);
const userData = {
email,
password: hashedPassword,
firstname,
lastname,
token
};
const response = await client.request(CreateNextUserMutation, { userData });
if (!response?.CreateNextUser?.id) {
res.status(500);
}
res.status(200).json({ token });
}

The SignIn API

In the core SignIn function we will:

  1. Run a query in Hygraph to getUserByEmail.

  2. Compare the password from sign-in form and the password stored in our database.

  3. Assign a fresh token if the passwords match and

    • Store it in Hygraph Database

    • Store it inside the request session

    • Return it back to the client

We’ve wrapped this SignIn function inside withIronSessionApiRoute so that we can make use of req.session for server side auth.


SignIn API - pages/api/auth/signin.js
import { withIronSessionApiRoute } from 'iron-session/next';
import { GraphQLClient, gql } from 'graphql-request';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
const cookie = {
cookieName: process.env.COOKIE_NAME,
password: process.env.COOKIE_PASSWORD,
cookieOptions: { secure: process.env.NODE_ENV === 'production' },
};
const { GRAPHCMS_URL, GRAPHCMS_PERMANENTAUTH_TOKEN, JWT_SECRET } = process.env;
const client = new GraphQLClient(GRAPHCMS_URL, {
headers: {
Authorization: `Bearer ${GRAPHCMS_PERMANENTAUTH_TOKEN}`,
},
});
const getUserByEmailQuery = gql`
query getUserByEmailQuery($email: String!) {
nextUser(where: { email: $email }, stage: DRAFT) {
id
email
password
}
}
`;
const updateUserMutation = gql`
mutation updateUser($where:NextUserWhereUniqueInput!, $data: NextUserUpdateInput!){
updateNextUser(data:$data, where:$where){
token,
email
}
}`;
export default withIronSessionApiRoute(
async function signIn(req, res) {
const { email, password } = req.body;
if (!email || !password) {
res.status(400).end();
return;
}
const getUserResponse = await client.request(getUserByEmailQuery, { email });
const { nextUser } = getUserResponse;
if (!nextUser) {
res.status(400).end();
return;
}
const { password: hashedPassword } = nextUser;
const isMatch = await bcrypt.compare(password, hashedPassword);
if (!isMatch) {
res.status(400).end();
return;
}
const token = jwt.sign({ email }, JWT_SECRET, { expiresIn: 36005 });
const updateUserResponse = await client.request(updateUserMutation, { where: { email }, data: { token } });
const { updateNextUser } = updateUserResponse;
if (!updateNextUser?.token) {
res.status(500).end();
return;
}
req.session.user = {
token: updateNextUser.token
};
await req.session.save();
res.status(200).json({ token: updateNextUser.token });
},
cookie
);

The GetUser API

GetUser API will be used by both Static and SSR pages. It will:

  1. Extract the jwt-token sent by the client from the request header

  2. Decode the jwt-token to get the user email & will get the user from Hygraph.

  3. Send appropriate response back to the client.

GetUser API - pages/api/auth/getuser.js

import { GraphQLClient, gql } from 'graphql-request';
import jwt from 'jsonwebtoken';
const { GRAPHCMS_URL, GRAPHCMS_PERMANENTAUTH_TOKEN, JWT_SECRET } = process.env;
const client = new GraphQLClient(GRAPHCMS_URL, {
headers: {
Authorization: `Bearer ${GRAPHCMS_PERMANENTAUTH_TOKEN}`,
},
});
const getUserByEmailQuery = gql`
query getUserByEmailQuery($email: String!) {
nextUser(where: { email: $email }, stage: DRAFT) {
email
firstname
lastname
}
}
`;
export default async function GetAuthenticatedUser(req, res) {
const defaultReturnObject = { authenticated: false, user: null };
try {
const token = String(req?.headers?.authorization?.replace('Bearer ', ''));
const decoded = jwt.verify(token, JWT_SECRET);
const getUserResponse = await client.request(getUserByEmailQuery, { email: decoded.email });
const { nextUser } = getUserResponse;
if (!nextUser) {
res.status(400).json(defaultReturnObject);
return;
}
res.status(200).json({ authenticated: true, user: nextUser });
}
catch (err) {
console.log('GetAuthenticatedUser, Something Went Wrong', err);
res.status(400).json(defaultReturnObject);
}
}

The SignOut API

Just a small function which destroys the session on the server side.

SignOut API - pages/api/auth/signout.js

import { withIronSessionApiRoute } from 'iron-session/next';
const cookie = {
cookieName: process.env.COOKIE_NAME,
password: process.env.COOKIE_PASSWORD,
cookieOptions: { secure: process.env.NODE_ENV === 'production' },
};
export default withIronSessionApiRoute(
function signOut(req, res) {
req.session.destroy();
res.status(200).json({ ok: true });
},
cookie
);

Pheww! Too much backend work! Don’t worry we’re already halfway there, It’ll pay off ;)


Before moving on to frontend pages, please create these common files at the same paths as present in the repository.

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.


SignUp - pages/signup.jsx

In the Sign up page, we

  • Check if the user is already signed in, if yes we redirect the user to the home page.

  • When a user submits the Sign up form, we call our SignUp API.

  • On receiving proper response we redirect the user to SignIn Page.

SignIn - pages/signin.jsx

Similarly, in the Sign in page, we

  • Check if the user is already signed in, if yes we redirect the user to the home page.

  • When a user submits the Sign in form, we call our SignIn API.

  • On receiving a token from our SignIn API

  • We store the token in local storage

  • Redirect the user to Home page

Layout

We’ll need a common Layout Component that will be used by both our Static and Server Side Pages.

  • It will have a Navigation Bar with a LogOut button.

  • When a user hits Logout it will remove the token from the browser’s local storage and call the SignOut API.

Client Side Authentication - In Action

So after all this work, let’s connect the dots and see client side Authentication in action!


Home Page - pages/index.jsx
import React from 'react';
import { useUser } from '../lib/customHooks';
import Layout from '../components/Layout';
export default function Home() {
const { user, authenticated } = useUser();
if (!user || !authenticated) {
return <Layout>
<div className="p-16">
<div className="text-2xl mb-4 font-bold text-blue-900">Home - Client Side Auth</div>
<div className="ml-2 w-8 h-8 border-l-2 rounded-full animate-spin border-blue-900" />
</div>
</Layout>;
}
return (
<Layout>
<div className="p-16">
<div className="text-2xl mb-4 font-bold text-blue-900">Home - Client Side Auth</div>
{
user &&
<div>
<div className="text-lg mb-2"> User Details </div>
<div className="flex">
<div className="w-24 font-medium">
<div> Email : </div>
<div> Firstname : </div>
<div> Lastname : </div>
</div>
<div>
<div> {user.email} </div>
<div> {user.firstname} </div>
<div> {user.lastname} </div>
</div>
</div>
</div>
}
</div>
</Layout>
);
}

Custom Hook - lib/customHooks.js
import { useState, useEffect } from 'react';
import { getAuthenticatedUser } from './common';
import { APP_ROUTES } from '../utils/constants';
import Router from 'next/router';
export function useUser() {
const [user, setUser] = useState(null);
const [authenticated, setAutenticated] = useState(false);
useEffect(() => {
async function getUserDetails() {
const { authenticated, user } = await getAuthenticatedUser();
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

  1. Browser requests for the index page.

  2. Our Next App immediately returns a Static Page which renders a loading state.

  3. The API call to the backend API happens from the useUser hook from the client (browser).

  4. 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.

Home - Client Side Auth loading (1).jpeg


Home - Client Side Auth (1).jpeg



  • 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.

  • You can try this exercise with the live demo too.

Server Side Authentication - In Action

Profile Page - pages/profile.jsx
import React from 'react';
import { API_ROUTES, APP_ROUTES } from '../utils/constants';
import { withIronSessionSsr } from 'iron-session/next';
import Layout from '../components/Layout';
import axios from 'axios';
const cookie = {
cookieName: process.env.COOKIE_NAME,
password: process.env.COOKIE_PASSWORD,
cookieOptions: { secure: process.env.NODE_ENV === 'production' },
};
export const getServerSideProps = withIronSessionSsr(
async function getServerSideProps({ req }) {
const API_SERVER_URL = process.env.API_SERVER_URL;
const defaultReturnObject = {
redirect: {
destination: APP_ROUTES.SIGN_IN,
permanent: false,
}
};
try {
let userSession = req.session.user;
if (!userSession?.token) {
return defaultReturnObject;
}
const { token } = userSession;
const response = await axios({
method: 'POST',
url: `${API_SERVER_URL}${API_ROUTES.GET_USER}`,
headers: {
Authorization: `Bearer ${token}`
}
});
const { authenticated, user } = response.data;
if (!authenticated || !user) {
return defaultReturnObject;
}
return {
props: {
user
},
};
}
catch (error) {
console.log('Profile Page, getServerSideProps, Something Went Wrong', error);
return defaultReturnObject;
}
},
cookie
);
export default function Profile({ user }) {
return (
<Layout>
<div className="p-16">
<div className="text-2xl mb-4 font-bold text-blue-900">Profile - Server Side Auth</div>
{ user &&
<div>
<div className="text-lg mb-2"> User Details </div>
<div className="flex">
<div className="w-24 font-medium">
<div> Firstname: </div>
<div> Lastname: </div>
<div> Email: </div>
</div>
<div>
<div> {user.firstname} </div>
<div> {user.lastname} </div>
<div> {user.email} </div>
</div>
</div>
</div>
}
</div>
</Layout>
);
}


Here we’re implementing the server-side authentication flow which goes something like this:

  1. Browser requests for the profile page.

  2. Our Next app SSR Profile Page authenticates that request on the server itself

  3. 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.
  4. 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.

    Profile - Server Side Auth (1).jpeg

  • 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

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.