DEV Community

Joel Marinho
Joel Marinho

Posted on

How to Handle GraphQL with React Query: Adding Security Headers

Hey there! Welcome back! Hopefully, you’ve had a chance to read my previous article on handling GraphQL with React Query. If not, don’t worry! Here’s the link to catch up (https://medium.com/@joeldeveloper2011140/how-to-integrate-react-query-with-graphql-for-efficient-caching-part-2-529744130836).

But wait, I realized I missed something important in that post. In real-world projects, security is everything. Whenever we interact with an API, we often need to provide authentication tokens or API keys in the headers, or maybe even add custom headers for specific actions. 😅

So, to make sure you’re covered, here's how you can integrate security headers with graphql-request and react-query if you’re following along from the article:

Adding Headers with graphql-request and React Query

If you’ve already read my previous article, this will feel like a quick refresher. If not, no worries, let’s dive right in!

First, let’s use the graphql-request library with react-query and inject headers such as an API key. Here’s a sample implementation for your useApiGetUsers hook:

`import request from "graphql-request";
import { useQuery } from "@tanstack/react-query";
import { GRAPHQL_API_URL } from "../../../constants";
import { GetUserSchema } from "./users.schema";

interface IUseApiGetUsersParams {
search: string;
}

interface IUseApiGetUserResponse {
User: {
about: string;
name: string;
id: number;
avatar: {
large: string;
};
siteUrl: string;
};
}

export const useApiGetUsers = (searchItem: string = "") => {
const { data: user, isLoading: isGettingUser } = useQuery({
queryKey: ["user", searchItem],
queryFn: async () => {
const response = await request<
IUseApiGetUserResponse,
IUseApiGetUsersParams
>(
GRAPHQL_API_URL,
GetUserSchema,
{ search: searchItem },
{ "api-key": "bla bla bla bla" } // Here's the key!
);
return response?.User;
},
});

return {
user,
isGettingUser,
};
}; `

Now, you can send custom headers (like your api-key) to your GraphQL API when making requests. Boom—just like that, you've added security to your GraphQL calls. 🚀

Reduce Duplication with a GraphQL Client

Now, let's talk about reducing code duplication. If you’re working on a larger project, you might want to create a GraphQL client that you can reuse across your app. This will prevent you from having to manually add headers every time you make a request.

I could have gone the extra mile and created a reusable GraphQLClient in this demo, but I kept it simple for now. But hey, if you want to keep your code neat and DRY (Don’t Repeat Yourself, folks), here’s how you can set up a GraphQL client:

`
import { GraphQLClient } from "graphql-request";

const graphQlClient = new GraphQLClient(GRAPHQL_API_URL, {
headers: {
"api-key": "bla bla bla", // Put your API key here
},
});
`
Now, instead of adding headers manually to each graphql-request, you can reuse the graphQlClient throughout your project. Just call it wherever you need a request, and boom, no more repeating code! 🙌

Wrapping It Up

Alright, folks, that’s all for today! You've learned how to:

  1. Add custom headers like api-key to your GraphQL requests.

  2. Keep things DRY by using a reusable GraphQLClient.

Before I sign off, I want to leave you with a quick tip: Always check out the GraphQLClient itself for more options and parameters—it’s like the Swiss Army knife of GraphQL requests! 🔪✨

Thanks for reading, and happy coding! Now go and make your GraphQL queries secure and efficient—because who needs security flaws in their app, right? 😜

That’s all folks! 🎉

Top comments (0)