Giter VIP home page Giter VIP logo

howto-gql-nextjs's Introduction

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.

howto-gql-nextjs's People

Contributors

ddeltree avatar

Stargazers

 avatar Kirill Tarasov avatar Abdul Hamid Achik López avatar Giorgia Bosello avatar

Watchers

Abdul Hamid Achik López avatar  avatar  avatar

howto-gql-nextjs's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.