5

We have a headless website with a front end based on a Next.js starter template. We use connected GraphQL calls for certain search and filter functionalities, allowing users to interact with the site (e.g., filtering), and we retrieve the results via GraphQL.

Since these calls are client-side, the API key is exposed in the request headers, as shown below.

The following screenshot is from local development.

Screenshot: GraphQL endpoint from the environment file.

enter image description here

Screenshot: Issue – API key is exposed in the request headers.

enter image description here

1 Answer 1

5

We achieved this by following these steps:

Step 1: Hide the API Key in the Front End

Go to your GraphQL client factory file (/src/lib/graphql-client-factory/index.ts). The path may vary depending on your version, but the logic remains the same. Comment out the lines shown below. This change prevents GraphQL calls from sending the API key.

Screenshot below

enter image description here

Step 2: Attach the API Key on the Server Side

For GraphQL to function, an API key is required, so you’ll need to attach it on the server side. This way, it will not be exposed in front-end requests.

Go to next.config.js, and add the route with the appropriate API key as shown below. Be sure to update your GraphQL endpoint accordingly. Here’s an example of ours:

Screenshot below

enter image description here

Finally, validate that the API key is no longer exposed in front-end requests.

enter image description here

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.