Frequently Asked Questions

Technical Features & Capabilities

How does Hygraph work with NextAuth.js for user authentication?

Hygraph integrates with NextAuth.js to manage user authentication and profile data. By using the Hygraph Mutations API combined with Next.js and NextAuth.js, you can build user-facing applications that allow users to register and log in, with Hygraph serving as the database. The integration leverages NextAuth.js's credentials provider and session callbacks to store user IDs and fetch user-specific data. Learn more in the tutorial.

What is the benefit of using Hygraph for managing user-generated content?

Hygraph enables structured management of user-generated content, allowing seamless integration with authentication systems like NextAuth.js. This approach provides flexibility for developers and ensures that user profiles and data are securely stored and easily retrievable. Read more.

How does Hygraph handle user authentication with NextAuth.js?

Hygraph uses the callbacks configuration in NextAuth.js to store the userId on the session, enabling user-specific data fetching and updates. This allows each user to have a unique profile managed within Hygraph. See details.

What is the recommended way to handle authentication in the Hygraph and NextAuth.js integration?

The recommended approach is to use NextAuth.js with a credentials provider for authentication. This setup allows you to securely manage user sessions and profile data within Hygraph. Learn more.

How can I create Next.js authentication with NextAuth.js and Hygraph?

You can follow the step-by-step guide provided in the Hygraph blog to create Next.js authentication using NextAuth.js and Hygraph. The tutorial covers setting up protected account pages, fetching user details, adding user forms, and creating API routes for updating accounts. Read the guide.

How can I authenticate users in the Hygraph Todo App?

Users can be authenticated with NextAuth.js using email/password login. This allows for secure user management and integration with Hygraph's content platform. See the quickstart.

API & Integration

Does Hygraph provide an API for managing content?

Yes, Hygraph offers a powerful GraphQL API that allows you to fetch and manage content efficiently. You can learn more about the API and its capabilities at the Hygraph API Reference.

What integrations does Hygraph support?

Hygraph supports a wide range of integrations, including hosting and deployment platforms (Netlify, Vercel), eCommerce solutions (BigCommerce, commercetools, Shopify), 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 a full list, visit the Hygraph Integrations 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 all users. For more details, visit the Hygraph Security Features page.

How does Hygraph ensure data security and compliance?

Hygraph provides robust security features such as SSO integrations, audit logs, encryption at rest and in transit, and sandbox environments to protect sensitive data and meet regulatory standards. For more information, visit the Hygraph Security Features page.

Getting Started & Implementation

How easy is it to get started with Hygraph?

Hygraph is designed for ease of use, even for non-technical users. You can sign up for a free-forever account and access comprehensive documentation, video tutorials, and onboarding guides. Customers have praised Hygraph for its intuitive interface and logical user experience. Get started here.

What training and technical support does Hygraph offer?

Hygraph provides 24/7 support via chat, email, and phone. Enterprise customers receive dedicated onboarding and expert guidance. All users can access detailed documentation, video tutorials, and a community Slack channel for further assistance. Contact support.

How long does it take to implement Hygraph?

Implementation is fast and straightforward. For example, Top Villas launched a new project in just 2 months from the initial touchpoint. The platform is designed for quick onboarding and rapid deployment. Read the case study.

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 more details, visit the pricing page.

Use Cases & Customer Success

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. Companies that benefit most include modern software companies, enterprises looking to modernize, and brands aiming to scale across geographies or improve development velocity. See case studies.

Can you share specific case studies or success stories of customers using Hygraph?

Yes. Komax achieved a 3X faster time to market, Autoweb saw a 20% increase in website monetization, Samsung improved customer engagement with a scalable platform, and Dr. Oetker enhanced their digital experience using MACH architecture. Explore more success stories.

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. See all industries.

Who are some of Hygraph's customers?

Notable customers include Sennheiser, HolidayCheck, Ancestry, Samsung, Dr. Oetker, Epic Games, Bandai Namco, Gamescom, Leo Vegas, and Clayton Homes. See more customer stories.

Performance & Business Impact

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. These benefits help businesses modernize their tech stack and achieve operational efficiency. Learn more.

How does Hygraph optimize content delivery performance?

Hygraph emphasizes optimized content delivery performance, which directly impacts user experience, engagement, and search engine rankings. Rapid content distribution and responsiveness help reduce bounce rates and increase conversions. Read more.

Documentation & Resources

Where can I find technical documentation for Hygraph?

Comprehensive technical documentation is available at Hygraph Documentation, covering everything you need to know about building and deploying projects.

What kind of content can I find in the Hygraph Blog?

The Hygraph Blog includes developer tutorials, latest updates, and essential guides to content modeling. Visit the Blog section for news and insights.

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

Working with NextAuth.js & User Generated Content

Manage user generated profile data with NextAuth.js, and Hygraph.
Jamie Barton

Written by Jamie 

Dec 09, 2021
NextAuth.js with Hygraph

In the previous article, I taught how to connect NextAuth.js with Hygraph, using the credentials provider. If you want to follow along with this tutorial, you should follow the steps in that article first.

If you'd rather skip to the good part, you can view a demo, or browse the code on GitHub.

Now that we've authenticated, let's give logged in users the ability to update their profile (such as a name, and bio). Here's what we'll be building:

Account area preview

#1. Create a Protected Account Page

Inside of your project pages directory, create the file account.js (or .ts if you're using TypeScript).

Inside of here, we'll use getSession from NextAuth.js to get the session from our users request. If there's no session, we'll redirect them to the index page. Let's do this server side, as we'll next

import { getSession } from 'next-auth/react';
export async function getServerSideProps(context) {
const session = await getSession(context);
if (!session) {
return {
redirect: {
destination: '/',
permanent: false,
},
};
}
return {
props: {},
};
}
export default function AccountPage() {
return (
<h1>My Account</h1>
)
}

If you attempt to visit [http://localhost:3000/account](http://localhost:3000/account) you'll be redirect to the index if you aren't logged in.

#2. Fetch User Details

We want to pre-populate a form users can submit to update their account. We'll need to update pages/api/auth/[...nextauth].js with a callbacks configuration object, so we can store the userId on our session.

Add the following below the providers array.

callbacks: {
async session({ session, token }) {
session.userId = token.sub;
return Promise.resolve(session);
},
},

Now back inside of pages/api/account.js let's update our getServerSideProps method to fetch our account from Hygraph.

I've gone ahead and refactored the GraphQLClient we made previously to be inside of it's own file, and imported that from the folder lib in our project.

See refactored code
// lib/hygraph.js
import { GraphQLClient } from 'graphql-request';
export const hygraphClient = new GraphQLClient(process.env.HYGRAPH_ENDPOINT, {
headers: {
Authorization: `Bearer ${process.env.HYGRAPH_TOKEN}`,
},
});

import { hygraphClient } from '../lib/hygraph';

We'll need to import gql from graphql-request and define a query to fetch a single instance of our NextAuthUser entry:

import { gql } from 'graphql-request';
const GetUserProfileById = gql`
query GetUserProfileById($id: ID!) {
user: nextAuthUser(where: { id: $id }) {
name
bio
}
}
`;

Now, inside of getServerSideProps add the following, and replace the returned props with:

const { user } = await hygraphClient.request(GetUserProfileById, {
id: session.userId,
});
return {
props: {
user,
},
};
See full code for function
export async function getServerSideProps(context) {
const session = await getSession(context);
if (!session) {
return {
redirect: {
destination: '/',
permanent: false,
},
};
}
const { user } = await hygraphClient.request(GetUserProfileById, {
id: session.userId,
});
return {
props: {
user,
},
};
}

#3. Add the User Form

Now, we've got the user fetched for our form; we need to populate a form with the data fetched from the above.

You could use useState from React to manage the values, but let's include a handy form library to do this for us.

You'll need to install react-hook-form to continue:

npm install -E react-hook-form

Then inside of our account.js file import it!

import { useForm } from 'react-hook-form';

You'll also want to grab user from the AccountPage props:

export default function AccountPage({ user }) {
// ...
}

We can then invoke useForm and pass it the defaultValues:

const { handleSubmit, register } = useForm({ defaultValues: user });

Now let's add the form inside of render:

<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="name">Name</label>
<br />
<input
type="text"
name="name"
{...register('name', { required: true })}
placeholder="name"
id="name"
/>
</div>
<div>
<label htmlFor="bio">Bio</label>
<br />
<textarea
name="bio"
{...register('bio')}
placeholder="Short bio"
id="bio"
rows={7}
/>
</div>
<div>
<button type="submit">Save profile</button>
</div>
</form>

We're almost there! If you try to load the page now, you'll notice we're missing the function onSubmit. We should define this inside of the page so our form knows what to do when submitted.

const onSubmit = async ({ name, bio }) => {
try {
const res = await fetch('/api/update-account', {
method: 'POST',
body: JSON.stringify({ name, bio }),
});
if (!res.ok) {
throw new Error(res.statusText);
}
} catch (err) {
console.log(err);
}
};

That's it for our form! If you submit this form now you'll noticed that an error is returned that /api/update-account doesn't exist.

View the full code
import { gql } from 'graphql-request';
import { useForm } from 'react-hook-form';
import { getSession } from 'next-auth/react';
import { hygraphClient } from '../lib/hygraph';
import Header from '../components/header';
const GetUserProfileById = gql`
query GetUserProfileById($id: ID!) {
user: nextAuthUser(where: { id: $id }) {
name
email
bio
}
}
`;
export async function getServerSideProps(context) {
const session = await getSession(context);
if (!session) {
return {
redirect: {
destination: '/',
permanent: false,
},
};
}
const { user } = await hygraphClient.request(GetUserProfileById, {
id: session.userId,
});
return {
props: {
user,
},
};
}
export default function AccountPage({ user }) {
const { handleSubmit, register } = useForm({ defaultValues: user });
const onSubmit = async ({ name, bio }) => {
try {
const res = await fetch('/api/update-account', {
method: 'POST',
body: JSON.stringify({ name, bio }),
});
if (!res.ok) {
throw new Error(res.statusText);
}
} catch (err) {
console.log(err);
}
};
return (
<div>
<Header />
<h1>My Account</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="name">Name</label>
<br />
<input
type="text"
name="name"
{...register('name', { required: true })}
placeholder="name"
id="name"
/>
</div>
<div>
<label htmlFor="bio">Bio</label>
<br />
<textarea
name="bio"
{...register('bio')}
placeholder="Short bio"
id="bio"
rows={7}
/>
</div>
<div>
<button type="submit">Save profile</button>
</div>
</form>
</div>
);
}

#4. Create API Route for Updating Account

All that's left to do is create the API route that takes the submitted JSON values, and passes them onto Hygraph to update.

Inside of the new file pages/api/update-account.js let's define a GraphQL mutation we can use to update our account by the ID of the logged in user.

import { gql } from 'graphql-request';
const UpdateNextAuthUser = gql`
mutation UpdateNextAuthUser($userId: ID!, $name: String, $bio: String) {
user: updateNextAuthUser(
data: { name: $name, bio: $bio }
where: { id: $userId }
) {
id
name
email
bio
}
}
`;

We'll next want to export an async function that inside of that we check if the user is logged in, and if not, send an error.

import { getSession } from 'next-auth/react';
export default async (req, res) => {
const session = await getSession({ req });
if (session) {
const { name, bio } = JSON.parse(req.body);
// We'll update this next
} else {
res.send({
error: 'You must be sign in to update your account.',
});
}
};

If you head back to /account and submit the form, we'll no longer have an error the page is missing, but nothing will happen. Let's fix that!

Inside of the if statement above, let's make a request to Hygraph.

const { user } = await hygraphClient.request(UpdateNextAuthUser, {
userId: session.userId,
name,
bio,
});
res.json(user);

You'll also want to import the hygraphClient:

import { hygraphClient } from '../../lib/hygraph';
View the full code
import { gql } from 'graphql-request';
import { getSession } from 'next-auth/react';
import { hygraphClient } from '../../lib/hygraph';
const UpdateNextAuthUser = gql`
mutation UpdateNextAuthUser($userId: ID!, $name: String, $bio: String) {
user: updateNextAuthUser(
data: { name: $name, bio: $bio }
where: { id: $userId }
) {
id
name
email
bio
}
}
`;
export default async (req, res) => {
const session = await getSession({ req });
if (session) {
const { name, bio } = JSON.parse(req.body);
const { user } = await hygraphClient.request(UpdateNextAuthUser, {
userId: session.userId,
name,
bio,
});
res.json(user);
} else {
res.send({
error: 'You must be sign in to update your account.',
});
}
};

That's it! You will now be able to login, update your account, and persist the data to your Hygraph project.

Each time a user signs into your account they'll have their own profile.

Blog Author

Jamie Barton

Jamie Barton

Jamie is a software engineer turned developer advocate. Born and bred in North East England, he loves learning and teaching others through video and written tutorials. Jamie currently publishes Weekly GraphQL Screencasts.

Share with others

Sign up for our newsletter!

Be the first to know about releases and industry news and insights.