DEV Community

Pieter Bergwerff
Pieter Bergwerff

Posted on

How to integrate GraphQL at the backend of NextJS

Since version 9 of NextJS it's now possible to setup express api routes for your application. You can export a express instance from the /api route.

It's relatively easy to implement GraphQL as your backend service. All you need is apollo-server-micro package from npm.

npm i apollo-server-micro --save
Enter fullscreen mode Exit fullscreen mode

Put following contents in /pages/api/index.js:

import { ApolloServer, gql } from "apollo-server-micro";

const typeDefs = gql`
  type Query {
    hello: String!
  }
`;

const resolvers = {
  Query: {
    hello: () => {
      return "welcome!";
    },
  }
};

const apolloServer = new ApolloServer({
  typeDefs,
  resolvers,
  context: () => ({}),
});

export default apolloServer.createHandler({ path: "/api" });

export const config = {
  api: {
    bodyParser: false,
  },
};

Enter fullscreen mode Exit fullscreen mode

Now npm run dev your project and you will see the Apollo GraphQL playground running at http://localhost:3000/api.

Top comments (0)