GraphQL Yoga Plugin system to protect your API
Learn how to use the GraphQL Yoga Plugin system to protect requests using API keys with Unkey in this video tutorial.
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;56 if (!token) {7 throw createGraphQLError("No API Key provided");8 }910 const { result, error } = await verifyKey(token);1112 if (error) {13 throw createGraphQLError(error.message);14 }1516 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";34const schema = createSchema({5 typeDefs: /* GraphQL */ `6 type Query {7 hello: String8 }9 `,10 resolvers: {11 Query: {12 hello: () => "world",13 },14 },15});1617const yoga = createYoga({ schema, plugins: [useUnkey()] });1819const server = createServer(yoga);2021server.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.
2500 verifications and 100K successful rate‑limited requests per month. No CC required.