Getting started
Forward browser GraphQL requests through your application’s server
Use createGraphQLHandler to forward browser requests through your application’s server. Server code can call the upstream API directly with the request client.
Before creating the route, install the package.
Create the route
Export a POST handler from a Next.js route file.
import { createGraphQLHandler } from "@octopus-energy/graphql/handler";
export const POST = createGraphQLHandler({
endpoint: "https://api.oexx-kraken.energy/v1/graphql/",
});Add authentication
For an authenticated Kraken endpoint, pass krakenRequestAuth as your onRequest callback. This example assumes your application already has a Better Auth instance configured with the Kraken plugins.
import { krakenRequestAuth } from "@octopus-energy/better-auth/request";
import { createGraphQLHandler } from "@octopus-energy/graphql/handler";
import { auth } from "#/lib/auth";
export const POST = createGraphQLHandler({
endpoint: "https://api.oexx-kraken.energy/v1/graphql/",
onRequest: krakenRequestAuth({ auth }),
});For a public endpoint, skip this step. If you use a different authentication setup, see Authenticate upstream requests for a custom callback example.
Make browser requests
Create a request function for the same-origin route:
import { createGraphQLRequest } from "@octopus-energy/graphql/request";
export const request = createGraphQLRequest("/api/graphql");With React Query configured, call it from a component:
"use client";
import { useQuery } from "@tanstack/react-query";
import { request } from "#/lib/graphql/client";
import { ElectricVehiclesQuery } from "#/lib/vehicles/get-vehicles";
export function Vehicles({ make }: { make: string }) {
const query = useQuery({
queryKey: ["vehicles", make],
queryFn: ({ signal }) => request(ElectricVehiclesQuery, { variables: { make }, signal }),
});
if (query.isPending) return <p>Loading…</p>;
if (query.error) return <p>Could not load results.</p>;
return (
<ul>
{query.data.electricVehicles?.map((group) => (
<li key={group?.make}>{group?.make}</li>
))}
</ul>
);
}