How to set x-hasura-admin-secret in Next.js

Cover Image for How to set x-hasura-admin-secret in Next.js
Ali Bentaleb
To leverage a quick REST and graphql API over data-sources In Next.js, Hasura is a very interesting solution to use.

Hasura provides instant GraphQL & REST APIs over new or existing data-sources. In this tutorial, we are going to explain how to set x-hasura-admin-secret key using node fetch and using Apollo client

Using node fetch

If you wish to fetch data without any extra packages, you can use node fetch to get the data from Hasura.

By default Hasura requires _x-hasura-admin-secret_ to be set in the header.

If not set, the error x-hasura-admin-secret/x-hasura-access-key required, but not found will be displayed

To resolve it , you need to :

  • Get x-hasura-admin-secret value by login to your hasura account, and go to the GraphiQL tab as the picture below is displayed

Hasura IHM graphiql tab x-hasura-admin-secret

Click on the eye button to display the x-hasura-admin-secret

  • Add the x-hasura-admin-secret as a key, its value in the headers object for fetch like below
const data = await fetch('https://your-hasura-url/graphql', {
	headers: {'x-hasura-admin-secret': 'your key from the GUI'},
	body: body,
	method: 'POST'
}).then((res) => res.json());

console.log('data', data);

Using Apollo Graphql

The Apollo Graphql client let you manage data with GraphQL more easily with a caching option

To avoid the error x-hasura-admin-secret/x-hasura-access-key required, but not found using apollo, you need to

  • Get the hasura x-hasura-admin-secret and value for the GUI like the image above
- Add the header in the Apollo client

In Next.js, to add the header for apollo client, use app.js file under pages folder.

The code will be like

import '../styles/globals.css';
import {
} from '@apollo/client';

import {setContext} from '@apollo/client/link/context';

const authLink = setContext((_, {headers}) => {
	return {
		headers: {
			'x-hasura-admin-secret': 'your key from the GUI'

const httpLink = createHttpLink({
	uri: 'https://your-hasura-url/graphql'

const client = new ApolloClient({
	link: authLink.concat(httpLink),
	cache: new InMemoryCache()

function MyApp({Component, pageProps}) {
	return (
		<ApolloProvider client={client}>
			<Component {...pageProps} />

export default MyApp;

The ApolloProvider will wrap every page in Next.js, and we set the client prop with our client.

The client is an ApolloClient, and we add the hasura key in the header


We have seen how to set the x-hasura-admin-secret using both node fetch and apollo GraphQL client in order to avoid the error x-hasura-admin-secret/x-hasura-access-key required, but not found.

How to solve router.query is u...How to build dynamic sitemap w...