Back to Templates

Protect GraphQL APIs with Unkey

GraphQL Yoga Plugin system to protect your API

Written by
notrab
Language
Typescript
GraphQL Yoga Plugin system to protect your API

GraphQL Yoga + Unkey

Learn how to use the GraphQL Yoga Plugin system to protect requests using API keys with Unkey in this video tutorial.

Usage

Create the following custom useUnkey plugin:

1function useUnkey(): Plugin {
2 return {
3 async onRequestParse({ request }) {
4 const token = request.headers.get("x-unkey-api-key") as string;
5
6 if (!token) {
7 throw createGraphQLError("No API Key provided");
8 }
9
10 const { result, error } = await verifyKey(token);
11
12 if (error) {
13 throw createGraphQLError(error.message);
14 }
15
16 if (!result.valid) {
17 throw createGraphQLError("API Key is not valid for this request");
18 }
19 },
20 };
21}

Now invoke useUnkey() and pass it to the Yoga plugins:

1import { createYoga, createGraphQLError, type Plugin } from "graphql-yoga";
2import { verifyKey } from "@unkey/api";
3
4const schema = createSchema({
5 typeDefs: /* GraphQL */ `
6 type Query {
7 hello: String
8 }
9 `,
10 resolvers: {
11 Query: {
12 hello: () => "world",
13 },
14 },
15});
16
17const yoga = createYoga({ schema, plugins: [useUnkey()] });
18
19const server = createServer(yoga);
20
21server.listen(4000, () => {
22 console.info("Server is running on http://localhost:4000/graphql");
23});

That's it! Make sure to pass your API key (provided by Unkey) for the header x-unkey-api-key with GraphQL requests.

Protect your API.
Start today.

2500 verifications and 100K successful rate‑limited requests per month. No CC required.