Using getServerSideProps for graphql-codegen mutation in nextjs

Viewed 241

I would like to perform a graphql mutation in getServerSideProps. I am using graphql-codegen to generate code from my graphql call. The code I use to perform my mutation is:

const [getTokenMutation, _] = useGetTokenMutation()
const token = await getTokenMutation({

When I move the working code from the function body to getServerSideProps I get the error: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons ...

To solve this I looked in to the graphql-codegen-apollo-next-ssr plugin for graphql-codegen. Unfortunately this only is generating code for the queries I have defined, not for the mutations.

How can I perform my mutation from getServerSideProps?

1 Answers

The server-side function are Node - not React, so you can't use React hooks in those functions.

You need to call the Apollo client query/mutation in each function. Next.js has multiple Apollo examples - here is one.


apollo-client.js

import { ApolloClient, InMemoryCache } from "@apollo/client";

export const client = new ApolloClient({
    uri: "https://example.com/graphql",
    cache: new InMemoryCache(),
    ...YOUR_SETTINGS
});

SomePage.js

import { gql } from "@apollo/client";
import { client } from "./apollo-client";

export async function getServerSideProps() {
    // query
    const { data } = await client.query({query: gql`query SomeQuery {...}`});
    // mutation
    const { data } = await client.mutate({ mutation: gql`mutation getToken {...}`, variables: {} });

}
Related