ddeltree / howto-gql-nextjs

Template and tutorial setup of Apollo Server & GraphQL on a Next.js API route with query IntelliSense and type-safety

Home Page:https://graph-ql-nextjs.vercel.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use this setup as a template

  1. Clone, install the dependencies and the Apollo GraphQL extension

  2. Write your custom types and resolvers in /graphql/

  3. Run npm run codegen to generate your types in /graphql/types/


Quick summary of the tutorial

  1. Codegen
npx create-next-app@latest . --ts
  # √ Would you like to use App Router? [Yes]

# Dependencies
npm i @apollo/client @apollo/server @as-integrations/next graphql encoding

npm i -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-resolvers

# Configure codegen on @/graphql/
npx graphql-code-generator init
npm install
  1. Apollo Server
  2. Apollo Client
  3. Apollo GraphQL Extension

Tutorial


1. Install the dependencies

npx create-next-app@latest . --ts
  # √ Would you like to use App Router? [Yes]

npm i @apollo/client @apollo/server @as-integrations/next graphql encoding

2. Create your type definitions and their resolvers

/graphql/schemas/queries.ts

import { gql } from '@apollo/client';

const queries = gql`
  type Query {
    hello: String!
  }
`;
export default queries;

/graphql/resolvers/queryResolvers.ts

const resolvers = {
  Query: {
    hello: () => 'Apollo Server is up & running on /graphql',
  },
};
export default resolvers;

3. Run the Apollo Server on localhost:3000/graphql

/app/graphql/route.ts

import { ApolloServer } from '@apollo/server';
import { startServerAndCreateNextHandler } from '@as-integrations/next';

import queryResolvers from '@/graphql/resolvers/queryResolvers';
import queries from '@/graphql/schemas/queries';

const server = new ApolloServer({
  resolvers: [queryResolvers /*...*/],
  typeDefs: [queries /*...*/],
  introspection: true,
});

const handler = startServerAndCreateNextHandler(server);
export const GET = handler;
export const POST = handler;

6. Configure the Apollo GraphQL extension for query IntelliSense

/apollo.config.js

module.exports = {
  client: {
    tagName: `graphql.`, // matches graphql(`...`)
    service: {
      name: 'local schema',
      url: 'http://localhost:3000/graphql',
    },
    includes: ['./app/**/*.ts{,x}' /*...*/],
    excludes: ['**/__tests__/**', 'graphql/**', 'node_modules/**', '*'],
  },
};

IntelliSense should be working now 👍

npm run dev


Making a query - set up the Apollo Client

/app/layout.tsx

//...
const client = new ApolloClient({
  uri: '/graphql',
  cache: new InMemoryCache(),
});

//...
<ApolloProvider client={client}>
  <body>{children}</body>
</ApolloProvider>;
//...

/app/page.tsx

//...
const GET_DATA = gql`
  query Query {
    hello
  }
`;

export default function Home() {
  const { loading, error, data } = useQuery(GET_DATA);
  //...
  return (
    //...
    <a href="/graphql">{data.hello}</a>
  );
}


Generate types from your schema

npm install -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-resolvers

Set up a configuration file to tell GraphQL Code Generator where and how to generate types

npx graphql-code-generator init
npm install
npm run codegen

Finally, type safety for the queried data 🥰

Tips

  • You can import your generated types from /graphql/types/graphql.ts
  • If you need the schema to be private, you should probably upload it to Apollo Studio and use that instead of the local schema, and disable introspection.
  • This configuration works well with Vercel, if you're thinking of deploying there.
  • Leave codegen in watch mode as you write the graphql-related stuff to get an instant feedback on the validity of it.
  • Sometimes the Apollo GraphQL extension takes too long to load the schema. If you run into that, reloading the window or re-saving its config file will probably take care of it.
  • Note that this extension configuration expects the apollo server to be running on localhost:3000/graphql.

About

Template and tutorial setup of Apollo Server & GraphQL on a Next.js API route with query IntelliSense and type-safety

https://graph-ql-nextjs.vercel.app


Languages

Language:TypeScript 87.5%Language:JavaScript 12.5%