How do I add authentication to a React application using Hygraph?
To add authentication to a React application with Hygraph, you set up a Hygraph schema for users, build a Node.js backend with JWT-based authentication, and connect your React frontend to the backend APIs. The backend handles sign-up, sign-in, and user verification, while the frontend manages token storage and protected routes. For a full walkthrough, see the Hygraph React Authentication Guide.
What schema should I create in Hygraph for user authentication?
You should create a User schema in Hygraph with fields such as firstname, lastname, email, and password. This schema serves as the foundation for storing user data and integrating with your backend authentication logic. See the example in the React Authentication tutorial.
How does the backend authentication flow work with Hygraph and Node.js?
The backend uses Node.js and Express to provide APIs for sign-up, sign-in, and user verification. Passwords are hashed with bcryptjs, JWT tokens are issued for authentication, and user data is managed via GraphQL requests to Hygraph. The backend exposes endpoints like /auth/signup, /auth/signin, and /auth/me for the frontend to interact with. See the code samples in the backend setup section.
How do I protect routes in my React frontend using authentication?
In your React app, you can use a custom hook (e.g., useUser()) to check for an authentication token and fetch the current user. Protected routes (like a dashboard) check if the user is authenticated and redirect to sign-in if not. The authentication token is typically stored in local storage and sent with API requests. See the frontend setup section for implementation details.
Where can I find the complete code for the React authentication demo?
What dependencies are required for the backend authentication setup?
The backend requires bcryptjs for password hashing, cors for cross-origin requests, dotenv for environment variables, express for the server, jsonwebtoken for JWT handling, graphql and graphql-request for interacting with Hygraph. See the backend setup guide for installation details.
How does the sign-up process work in this authentication flow?
During sign-up, the backend receives user details, hashes the password, creates a user in Hygraph via GraphQL, and returns a JWT token. The frontend collects user input and sends it to the /auth/signup endpoint. See the sign-up logic section for code and explanation.
How does the sign-in process work in this authentication flow?
For sign-in, the backend verifies the user's email and password, compares the password hash, and issues a new JWT token if successful. The frontend stores this token and uses it for authenticated requests. See the sign-in logic section for details.
How do I verify the current authenticated user in my React app?
The frontend sends the stored JWT token to the /auth/me endpoint. The backend verifies the token and returns the user object if valid. This logic is typically encapsulated in a custom React hook for reusability. See the custom hook example.
What are the main components of the React authentication demo?
The main components are SignUp, SignIn, and a protected Dashboard. The app uses React Router for navigation and custom hooks for authentication state management. See the component code for details.
How does the authentication token get stored and used in the frontend?
The authentication token (JWT) is stored in local storage after a successful sign-in. It is then sent with API requests to verify the user's identity and access protected routes. The useUser() hook checks for the token and fetches user details as needed.
How can I expand this authentication setup for enterprise use cases?
For enterprise applications, you may need advanced features like SSO, OAuth flows, fine-grained role-based authorization, and enhanced security. While the tutorial covers basic JWT authentication, Hygraph supports enterprise-grade features such as SSO integrations, granular permissions, and audit logs. Learn more at the Hygraph Secure Features page.
What are some common challenges when building authentication from scratch?
Building authentication from scratch can be complex and error-prone, especially for advanced requirements like SSO, OAuth, and role-based access. You must keep your APIs up-to-date with security standards and manage vulnerabilities. Many teams opt for managed solutions like AWS Cognito or Auth0 to avoid these challenges. See the conclusion section for more insights.
Can I use a different backend or database with Hygraph for authentication?
Yes, you can choose your own backend server and database. The tutorial demonstrates using Node.js and Hygraph, but the principles apply to other stacks as well. Hygraph's GraphQL API can be integrated with various backend technologies.
How do I handle password hashing and security in this setup?
Passwords are hashed using bcryptjs before being stored in Hygraph. This ensures that plain-text passwords are never saved, enhancing security. Always use secure password handling practices in production environments.
How can I test the authentication flow locally?
You can run the backend server with node index.js and the React frontend with npm start. Use the Sign Up and Sign In forms to register and authenticate users, and verify protected routes like the dashboard. See the demo repository for setup instructions.
What is the role of JWT tokens in this authentication setup?
JWT tokens are used to securely transmit user identity between the frontend and backend. After sign-in or sign-up, the backend issues a JWT token, which the frontend stores and sends with requests to access protected resources or verify the current user.
How can I customize the authentication logic for my own requirements?
You can expand the authentication logic by adding features like token expiry, password reset, email verification, or integrating with third-party auth providers. The provided code is modular and can be adapted to your needs. See the conclusion section for suggestions.
What are the best practices for securing authentication APIs?
Best practices include hashing passwords, using HTTPS, validating inputs, keeping JWT secrets secure, and regularly updating dependencies. For enterprise security, Hygraph offers features like audit logs, SSO, and granular permissions. See Hygraph Secure Features for more.
How does Hygraph support advanced authentication and authorization features?
Hygraph supports advanced features such as SSO integrations, granular permissions, audit logs, and encryption. These are essential for enterprise-grade security and compliance. Learn more at the Hygraph Secure Features page.
What are the limitations of the basic authentication setup in the tutorial?
The tutorial covers a minimal JWT-based authentication flow. For production, you may need to add features like token refresh, account lockout, multi-factor authentication, and integration with identity providers. Consider using Hygraph's enterprise features or third-party auth services for advanced needs.
Features & Capabilities
What features does Hygraph offer for content management and authentication?
Hygraph provides a GraphQL-native architecture, content federation, user-friendly tools, enterprise-grade security, and advanced features like SSO, granular permissions, audit logs, and Smart Edge Cache. These features support both basic and advanced authentication and content management needs. Learn more about Hygraph features.
Does Hygraph provide APIs for authentication and content management?
Yes, Hygraph offers multiple APIs, including Content API, High Performance Content API, MCP Server API, Asset Upload API, and Management API. These APIs support secure, efficient content and user management. See the API Reference Documentation for details.
What integrations does Hygraph support?
Hygraph integrates with Digital Asset Management systems (e.g., Aprimo, AWS S3, Bynder, Cloudinary, Imgix, Mux, Scaleflex Filerobot), Adminix, Plasmic, and supports custom integrations via SDKs and APIs. Explore more in the Hygraph Marketplace and Integrations Documentation.
How does Hygraph ensure high performance for content delivery?
Hygraph provides high-performance endpoints designed for low latency and high read-throughput. Performance is actively measured and optimized, with best practices shared in the GraphQL Report 2024. Learn more about endpoint improvements in the performance blog post.
What technical documentation is available for Hygraph?
Hygraph offers comprehensive documentation covering APIs, schema components, references, webhooks, and AI integrations. Access all resources at the Hygraph Documentation portal.
Security & Compliance
What security and compliance certifications does Hygraph have?
Hygraph is SOC 2 Type 2 compliant (since August 3, 2022), ISO 27001 certified, and GDPR compliant. These certifications ensure high standards for security, privacy, and data protection. See the Secure Features page for more details.
How does Hygraph protect my data?
Hygraph encrypts data at rest and in transit, provides regular backups, supports granular permissions, audit logs, SSO integrations, and offers dedicated hosting options. Security incidents can be reported through a dedicated process. Learn more at the Secure Features page.
Pricing & Plans
What pricing plans does Hygraph offer?
Hygraph offers three main plans: Hobby (free forever), Growth (from $199/month), and Enterprise (custom pricing). Each plan includes different features and limits. See the Hygraph Pricing page for full details.
What features are included in the free Hobby plan?
The Hobby plan includes 2 locales, 3 seats, 2 standard roles, 10 components, unlimited asset storage, 50MB per asset upload, live preview, and commenting workflow. Sign up for free.
What does the Growth plan cost and include?
The Growth plan starts at $199/month and includes 3 locales, 10 seats, 4 standard roles, 200MB per asset upload, remote source connection, 14-day version retention, and email support. Get started with Growth.
What is included in the Enterprise plan?
The Enterprise plan offers custom limits, advanced governance, scheduled publishing, dedicated infrastructure, SSO, multitenancy, instant backup recovery, custom workflows, and dedicated support. Try Enterprise for 30 days or request a demo.
Use Cases & Customer Success
Who can benefit from using Hygraph?
Hygraph is ideal for developers, product managers, content creators, marketers, solutions architects, enterprises, agencies, eCommerce, media, technology companies, and global brands. Its flexibility supports SaaS, eCommerce, media, healthcare, and more. See case studies for examples.
What industries use Hygraph?
Industries include SaaS, marketplace, education technology, media, healthcare, consumer goods, automotive, technology, fintech, travel, food and beverage, eCommerce, agencies, gaming, events, government, consumer electronics, engineering, and construction. See the case studies page for more.
Can you share some customer success stories with Hygraph?
Yes. Samsung built a scalable API-first app, Komax achieved 3x faster time to market, AutoWeb saw a 20% increase in monetization, and Voi scaled content across 12 countries. See all Hygraph case studies.
What business impact can I expect from using Hygraph?
Customers report improved operational efficiency, faster speed-to-market, cost savings, enhanced scalability, and better customer engagement. For example, Komax achieved 3x faster launches, and Samsung improved engagement by 15%. See case studies for more metrics.
How long does it take to implement Hygraph?
Implementation time varies by project. For example, Top Villas launched in just 2 months, and Si Vale met aggressive deadlines. Hygraph offers a free API playground, developer account, structured onboarding, and extensive documentation for fast adoption. See Top Villas case study.
What feedback have customers given about Hygraph's ease of use?
Customers praise Hygraph's intuitive UI, ease of setup, and ability for non-technical users to manage content independently. For example, "I'm not at all a technical guy, but I was able to start using it right away." See more feedback at Hygraph Try Headless CMS.
Competition & Differentiation
How does Hygraph compare to other CMS platforms?
Hygraph is the first GraphQL-native Headless CMS, offering content federation, user-friendly tools, and enterprise-grade features. It stands out for its flexibility, scalability, and ease of integration with modern tech stacks. Hygraph ranked 2nd out of 102 Headless CMSs in the G2 Summer 2025 report. See G2 report for details.
Why choose Hygraph over alternatives like Contentful or Sanity?
Hygraph's unique strengths include its GraphQL-native architecture, content federation (integrating multiple data sources without duplication), and proven ease of implementation. It is best for teams needing modern workflows, global content delivery, and enterprise security. See case studies for real-world comparisons.
In this article, we’ll explore with the help of a demo, how to set up authentication in a Create React App.
Last updated by Aagam
on Nov 04, 2024
Originally written by Aagam
Authentication and Authorization are crucial for any software to be built today. In this article, we’ll explore with the help of a demo, how to set up authentication in a Create React App. We will implement a basic straightforward JWT-based bearer token authentication.
To set up the base, we should begin by creating our User schema in Hygraph dashboard. We will keep fields like firstname, lastname, email, and password in the schema, it will look something like this:
Once this schema is configured, we can move on to build the backend Node.js Express API.
Node.js Backend Application
Base Setup
Do an npm initin a fresh folder to create a new application and install the following dependencies using npm install
We will be using bcryptjsto hash passwords, expressand corsto manage the backend API, dotenvto support environment variables via a .env file, jsonwebtokento sign, and decode the jwt-tokens for authentication, and finally graphql, graphql-requestto fetch data from Hygraph GraphQL API.
Let's begin with some base backend server setup.
Please add the following files
.env
JWT_SECRET=SUPERSECRET
JWT_EXPIRES_IN=1 hour
HYGRAPH_URL=VALUE
HYGRAPH_PERMANENTAUTH_TOKEN=VALUE
index.js
import'dotenv/config';
importappfrom'./app.js';
const port = process.env.PORT||4000;
app.listen(port,()=>{
console.log(`Backend API Ready On Port: ${port}`);
In a backend application we generally have Routes, Controllers and Services. Let us use the same framework to create three APIs that we will need, one to Sign Up, one to Sign In, and one to verify or get the user from an issued access token.
const user =awaitthis.authService.getCurrentUser(token);
res.status(200).json({authenticated:true, user });
}catch(err){
console.error("GET auth/me, Something Went Wrong:", err);
res.status(400).json(defaultReturnObject);
}
}
}
exportdefaultAuthController;
In all three functions of the class - signup, signin, getCurrentUser, we have done these steps:
Destructure input from the request.
Validate the input.
Call the service function to run the respective logic.
Get response from service and send it back to the client.
Catch and throw any run time errors.
Service
Finally, let us create the service file step by step and the first step would be to create the skeleton for our service file where the actual authentication logic will be placed for each API.
services/authService.js
importbcryptfrom"bcryptjs";
importjwtfrom"jsonwebtoken";
importgqlClientfrom"../graphql/gqlClient.js";
import{
CreateNextUserMutation,
GetUserByEmailQuery,
}from"../graphql/mutations.js";
const{JWT_SECRET,JWT_EXPIRES_IN}= process.env;
classAuthService{
asyncsignup(signupRequest){
// SIGNUP LOGIC
}
asyncsignin(email, password){
// SIGN IN LOGIC
}
asyncgetCurrentUser(token){
// GET CURRENT USER LOGIC
}
}
exportdefaultAuthService;
Now let us add and understand individual functions step by step, starting with the sign up function:
For Sign Up, we get the new user details from the controller, then we hash the password and save the user in the database, finally we create a jwt-token with the user details and send the token back to the client.
Moving on to the sign in functionality, here we will accept email and password, get the user details from our database, and compare the given and stored password hash with bcrypt. We throw an error if the passwords do not match, else we create a fresh jwt token and send it back to the client.
Finally, one API to get the currently authenticated user details from an existing access token. It will accept and verify the access token, and send the user object back if the token is valid. This idea of this getCurrentUser function can be expanded further as a middleware to verify your user before running the logic for all your other protected APIs in the backend.
Now go to the root of this setup and start the application with node index.js, you should be able to see that the backend app is now running, and with this our Authentication backend setup is complete!
To start a new React application using Create React App move to a fresh folder and type npx create-react-app frontend. To this app, add axios and react-router-dom dependencies. We’ll be using tailwind css for this app but feel free to use your own CSS/UI framework. To begin with a clean slate, clean up the create-react-app boilerplate css and test files.
The strategy here to handle authentication is that when we hit the backend SignIn API, it will give us an access token, we will save that token somewhere on the client side. Then on every route visit in the frontend we will just check if the token is present on the client side and if we are able to get the user by calling the GET /me API. We will write this logic inside a custom react hook for reusability.
First, please go through self explanatory code files and add them in your app as well
Now we will add a custom hook to check for the Authenticated user. This hook can be used inside any react component to get the Current Authenticated User.
const{ authenticated, user }=awaitgetAuthenticatedUser();
if(!authenticated){
navigate(APP_ROUTES.SIGN_IN);
return;
}
setUser(user);
setAutenticated(authenticated);
}
getUserDetails();
},[]);
return{ user, authenticated };
}
Components
Now we can have the main app with Routes and three simple components namely Sign In, Sign Up and a protected Route Dashboard that will be only accessible if the user is logged in.
console.log('Something went wrong during signing in: ', response);
return;
}
storeTokenInLocalStorage(response.data.token);
navigate(APP_ROUTES.DASHBOARD)
}
catch(err){
console.log('Some error occured during signing in: ', err);
}
finally{
setIsLoading(false);
}
};
return(
// MARKUP
);
}
exportdefaultSignIn;
That’s it! Try signing up a user with the Sign Up page, it will call our backend signup API and register the user in the database. After that, you can sign in using the above component. Once signed in, we store the token in local storage and then we redirect the user to some page that requires a user to be authenticated.
Let us build the Dashboard component which will be a protected route, we will make use of the useUser() custom hook that we made earlier to get the authenticated user.
If you delete the token from local storage and try to go to route /dashboardyou’ll be redirected to /signin the useUser() hook handles that redirection.
Well done, a complete application right from the database all the way to a React Frontend with Authentication is ready! If you’re looking to build a robust application that scales well in production, you might want to take a look how a create react app differs from Next.js, the production framework for React!
In this article, we went through the level one of building Authentication for full stack applications. We set up the database with a Hygraph schema, connected our backend app to it, created three APIs and connected three frontend components to those APIs. This was a very minimal and basic authentication setup, and something that every developer should have an idea about. This can be expanded further to support a number of use cases like fine grained authorization rules per API, expiry of tokens, security features can be further improved, and more.
However, enterprise application’s authentication & authorization requirements can become more complex over time. Managing multiple logins, revoking access, SSO Logins, OAuth flows, fine grained role based authorization rules, fingerprints, all these advanced features are required by many software products. In reality, it is quite difficult to build and manage Authentication and Authorization from scratch. OAuth flows can get tricky, you have to keep all your Auth API up-to-date with the latest standards and look out for all vulnerabilities in your system. If you build your own Auth, you have to maintain it responsibly as security issues are not something you can stall. That is why many teams who want to focus more on building their actual product and not be tangled with Authentication and Authorization workflows opt for services like AWS Cognito or Auth0.
Blog Authors
Aagam Vadecha
Aagam Vadecha
Share with others
Sign up for our newsletter!
Be the first to know about releases and industry news and insights.