How To Build A GraphQL Server Using Next.js API Routes

Next.js gives you the best developer experience with all the features you need for production. It provides a straightforward solution to build your API using Next.js API routes.

In this guide, we will be first learning what are API Routes, and then create a GraphQL server that retrieves the data from the Github API using the Next.js API Routes.

To get the most out of this tutorial, you need at least a basic understanding of GraphQL. Knowledge of Apollo Server would help but is not compulsory. This tutorial would benefit those who want to extend their React or Next.js skills to the server-side and be able to build as well their first full-stack app with Next.js and GraphQL.

So, let’s dive in.

What Are Next.js API Routes?

Next.js is a framework that enables rendering React apps on the client or/and the server. Since version 9, Next.js can now be used to build APIs with Node.js, Express, GrapQL, and so on. Next.js uses the file-system to treat files inside the folder pages/api as API endpoints. Meaning that, now, you will be able to access your API endpoint on the URL http://localhost:3000/api/your-file-name.

If you came from React and never used Next.js, this might be confusing because Next.js is a React framework. And as we already know, React is used to build front-end apps. So why use Next.js for backend apps and APIs?

Well, Next.js can both be used on the client and server sides because it is built with React, Node.js, Babel, and Webpack, and obviously, it should be usable on the server as well. Next.js relies on the server to enable API Routes and lets you use your favorite backend language even if it’s technically a React framework. Hopefully, you get it right.

So far, we have learned what API Routes are. However, the real question remains: why use Next.js to build a GraphQL Server? Why not use GraphQL or Node.js to do so? So, let’s compare Next.js API Routes to existing solutions for building APIs in the next section.

Next.js API Routes Versus REST And GraphQL

GraphQL and REST are great ways of building APIs. They are super popular and used by almost every developer nowadays. So, why use a React framework to build APIs? Well, the quick answer is that Next.js API Routes are on a different purpose because API Routes allows you to extend your Next.js App by adding a backend to it.

There are better solutions for building APIs such as Node.js, Express, GraphQL, and so on since they are focused on the backend. In my opinion, the API Routes should be coupled with a client-side to build up a full-stack app with Next.js. Using the API Routes to build a simple API is like underusing the power of Next.js because it’s a React framework that enables you to add a backend to it in no-time.

Consider the use-case when you need to add authentication to an existing Next App. Instead of building the auth part from scratch with Node.js or GraphQL, you can use API Routes to add authentication to your app, and it will still be available on the endpoint http://localhost:3000/api/your-file-name. The API Routes won’t increase your client-side bundle size because they are server-side only bundles.

However, Next.js API Routes are only accessible within the same-origin because API Routes do not specify Cross-Origin Resource Sharing (CORS) headers. You can still tweak the default behavior by adding CORS to your API — but it’s an extra setup. If you generate your Next App statically using next export — you won’t be able to use API Routes within your app.

So far, we have learned when API Routes might be a better solution compared to the like. Now, let’s get hands dirty and start building our GraphQL Server.

Setting Up

To start a new app with Next.js, we will go for Create Next App. It’s also possible to set up manually a new app with Webpack. You are more than welcome to do so. That being said, open your command-line interface and run this command:

npx create-next-app next-graphql-server

Next.js provides a starter template for API Routes. You can use it by executing the following command:

npx create-next-app --example api-routes api-routes-app

In this tutorial, we want to do everything from scratch, which is why we use Create Next App to start a new app and not the starter template. Now, structure the project as follows:

├── pages
|  ├── api
|  |  ├── graphql.js
|  |  ├── resolvers
|  |  |  └── index.js
|  |  └── schemas
|  |     └── index.js
|  └── index.js
├── package.json
└── yarn.lock

As we said earlier, the api folder is where our API or server lives. Since we will be using GraphQL, we need a resolver and a schema to create a GraphQL server. The endpoint of the server will be accessible on the path /api/graphql, which is the entry point of the GraphQL server.

With this step forward, we can now create the GraphQL Schema for our server.

Create The GraphQL Schemas

As a quick recap, a GraphQL schema defines the shape of your data graph.

Next, we need to install apollo-server-micro to use Apollo Server within Next.js.

yarn add apollo-server-micro

For npm

npm install apollo-server-micro

Now, let’s create a new GraphQL schema.

In api/schemas/index.js

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

export  const  typeDefs  =  gql`
    type  User {
        id: ID
        login: String
        avatar_url: String
    }

    type  Query {
        getUsers: [User]
        getUser(name: String!): User!
    }`

Here, we define a User type that describes the shape of a Github user. It expects an id of type ID, a login, and an avatar_url of type String. Then, we use the type on the getUsers query that has to return an array of users. Next, we rely on the getUser query to fetch a single user. It needs to receive the name of the user in order to retrieve it.

With this GraphQL Schema created, we can now update the resolver file and create the functions to perform these queries above.

Create The GraphQL Resolvers

A GraphQL resolver is a set of functions that allows you to generate a response from a GraphQL query.

To request data from the Github API, we need to install the axios library. So, open your CLI and execute this command:

yarn add axios

Or when using npm

npm install axios

Once the library is installed, let’s now add some meaningful code to the resolvers file.

In api/resolvers/index.js

import axios from "axios";

export const resolvers = {
  Query: {
    getUsers: async () => {
      try {
        const users = await axios.get("https://api.github.com/users");
        return users.data.map(({ id, login, avatar_url }) => ({
          id,
          login,
          avatar_url
        }));
      } catch (error) {
        throw error;
      }
    },
    getUser: async (_, args) => {
      try {
        const user = await axios.get(
          https://api.github.com/users/${args.name}
        );
        return {
          id: user.data.id,
          login: user.data.login,
          avatar_url: user.data.avatar_url
        };
      } catch (error) {
        throw error;
      }
    }
  }
};

As you can see here, we match the queries name defined earlier on the GraphQL Schema with the resolver functions. The getUsers function enables us to retrieve all users from the API and then return an array of users that needs to mirror the User type. Next, we use the getUser method to fetch a single user with the help of the name passed in as a parameter.

With this in place, we now have a GraphQL Schema and a GraphQL resolver — it’s time to combine them and build up the GraphQL Server.

Create The GraphQL server

A GraphQL server exposes your data as a GraphQL API. It gives clients apps the power to ask for exactly the data they need and nothing more.

In api/graphql.js

import  {  ApolloServer  }  from  "apollo-server-micro";
import  {  typeDefs  }  from  "./schemas";
import  {  resolvers  }  from  "./resolvers";

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

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

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

After importing ApolloServer, we use it to create a new instance and then pass in the schema and the resolver to create a GraphQL server. Next, we need to tell Next.js not to parse the incoming request and let GraphQL handle it for us. Finally, we use apolloServer to create a new handler, which means the path /api/graphql will serve as an entry point for our GraphQL server.

Unlike regular Apollo Server, Next.js handles the start of the server for us since it relies on server-side rendering. That is why, here, we don’t have to start the GraphQL server on our own.

Great! With this step forward, we can now test if the GraphQL server works.

Test The GraphQL Server

Once you browse to the root of the project, open it on the CLI, and then execute this command:

yarn dev

Or for npm

npm run dev

Now, visit http://localhost:3000/api/graphql and add the GraphQL query below to retrieve all users from Github.

{
  getUsers {
    id
    login
    avatar_url
  }
}

Let’s check if we can fetch a single user with this query.

query($name: String!){
  getUser(name:$name){
        login
    id
    avatar_url
  }
}

Great! Our server works as expected. We are done building a GraphQL server using Next.js API Routes.

Conclusion

In this tutorial, we walked through Next.js API Routes by first explaining what they are and then build a GraphQL server with Next.js. The ability to add a backend to Next.js apps is a really nice feature. It allows us to extend our apps with a real backend. You can even go further and connect a database to build a complete API using API Routes. Next.js definitely makes it easier to build a full-stack app with the API Routes.

You can preview the finished project on CodeSandbox.

Thanks for reading!

Further Resources

These useful resources will take you beyond the scope of this tutorial.

Get Started Building GraphQL APIs With Node

We all have a number of interests and passions. For example, I’m interested in JavaScript, 90’s indie rock and hip hop, obscure jazz, the city of Pittsburgh, pizza, coffee, and movies starring John Lurie. We also have family members, friends, acquaintances, classmates, and colleagues who also have their own social relationships, interests, and passions. Some of these relationships and interests overlap, like my friend Riley who shares my interest in 90’s hip hop and pizza. Others do not, like my colleague Harrison, who prefers Python to JavaScript, only drinks tea, and prefers current pop music. All together, we each have a connected graph of the people in our lives, and the ways that our relationships and interests overlap.

These types of interconnected data are exactly the challenge that GraphQL initially set out to solve in API development. By writing a GraphQL API we are able to efficiently connect data, which reduces the complexity and number of requests, while allowing us to serve the client precisely the data that it needs. (If you’re into more GraphQL metaphors, check out Meeting GraphQL at a Cocktail Mixer.)

In this article, we’ll build a GraphQL API in Node.js, using the Apollo Server package. To do so, we'll explore fundamental GraphQL topics, write a GraphQL schema, develop code to resolve our schema functions, and access our API using the GraphQL Playground user interface.

What is GraphQL?

GraphQL is an open source query and data manipulation language for APIs. It was developed with the goal of providing single endpoints for data, allowing applications to request exactly the data that is needed. This has the benefit of not only simplifying our UI code, but also improving performance by limiting the amount of data that needs to be sent over the wire.

What we’re building

To follow along with this tutorial, you’ll need Node v8.x or later and some familiarity with working with the command line. 

We’re going to build an API application for book highlights, allowing us to store memorable passages from the things that we read. Users of the API will be able to perform “CRUD” (create, read, update, delete) operations against their highlights:

  • Create a new highlight
  • Read an individual highlight as well as a list of highlights
  • Update a highlight’s content
  • Delete a highlight

Getting started

To get started, first create a new directory for our project, initialize a new node project, and install the dependencies that we’ll need:

# make the new directory
mkdir highlights-api
# change into the directory
cd highlights-api
# initiate a new node project
npm init -y
# install the project dependencies
npm install apollo-server graphql
# install the development dependencies
npm install nodemon --save-dev

Before moving on, let’s break down our dependencies:

  • apollo-server is a library that enables us to work with GraphQL within our Node application. We’ll be using it as a standalone library, but the team at Apollo has also created middleware for working with existing Node web applications in ExpresshapiFastify, and Koa.
  • graphql includes the GraphQL language and is a required peer dependency of apollo-server.
  • nodemon is a helpful library that will watch our project for changes and automatically restart our server.

With our packages installed, let’s next create our application’s root file, named index.js. For now, we’ll console.log() a message in this file:

console.log("📚 Hello Highlights");

To make our development process simpler, we’ll update the scripts object within our package.json file to make use of the nodemon package:

"scripts": {
  "start": "nodemon index.js"
},

Now, we can start our application by typing npm start in the terminal application. If everything is working properly, you will see 📚 Hello Highlights logged to your terminal.

GraphQL schema types

A schema is a written representation of our data and interactions. By requiring a schema, GraphQL enforces a strict plan for our API. This is because the API can only return data and perform interactions that are defined within the schema. The fundamental component of GraphQL schemas are object types. GraphQL contains five built-in types:

  • String: A string with UTF-8 character encoding
  • Boolean: A true or false value
  • Int: A 32-bit integer
  • Float: A floating-point value
  • ID: A unique identifier

We can construct a schema for an API with these basic components. In a file named schema.js, we can import the gql library and prepare the file for our schema syntax:

const { gql } = require('apollo-server');

const typeDefs = gql`
  # The schema will go here
`;

module.exports = typeDefs;

To write our schema, we first define the type. Let’s consider how we might define a schema for our highlights application. To begin, we would create a new type with a name of Highlight:

const typeDefs = gql`
  type Highlight {
  }
`;

Each highlight will have a unique ID,  some content, a title, and an author. The Highlight schema will look something like this:

const typeDefs = gql`
  type Highlight {
    id: ID
    content: String
    title: String
    author: String
  }
`;

We can make some of these fields required by adding an exclamation point:

const typeDefs = gql`
  type Highlight {
    id: ID!
    content: String!
    title: String
    author: String
  }
`;

Though we’ve defined an object type for our highlights, we also need to provide a description of how a client will fetch that data. This is called a query. We’ll dive more into queries shortly, but for now let’s describe in our schema the ways in which someone will retrieve highlights. When requesting all of our highlights, the data will be returned as an array (represented as [Highlight]) and when we want to retrieve a single highlight we will need to pass an ID as a parameter.

const typeDefs = gql`
  type Highlight {
    id: ID!
    content: String!
    title: String
    author: String
  }
  type Query {
    highlights: [Highlight]!
    highlight(id: ID!): Highlight
  }
`;

Now, in the index.js file, we can import our type definitions and set up Apollo Server:

const {ApolloServer } = require('apollo-server');
const typeDefs = require('./schema');

const server = new ApolloServer({ typeDefs });

server.listen().then(({ url }) => {
  console.log(`📚 Highlights server ready at ${url}`);
});

If we’ve kept the node process running, the application will have automatically updated and relaunched, but if not, typing npm start  from the project’s directory in the terminal window will start the server. If we look at the terminal, we should see that nodemon is watching our files and the server is running on a local port:

[nodemon] 2.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
📚 Highlights server ready at http://localhost:4000/

Visiting the URL in the browser will launch the GraphQL Playground application, which provides a user interface for interacting with our API.

GraphQL Resolvers

Though we’ve developed our project with an initial schema and Apollo Server setup, we can’t yet interact with our API. To do so, we’ll introduce resolvers. Resolvers perform exactly the action their name implies; they resolve the data that the API user has requested. We will write these resolvers by first defining them in our schema and then implementing the logic within our JavaScript code. Our API will contain two types of resolvers: queries and mutations.

Let’s first add some data to interact with. In an application, this would typically be data that we’re retrieving and writing to from a database, but for our example let’s use an array of objects. In the index.js file add the following:

let highlights = [
  {
    id: '1',
    content: 'One day I will find the right words, and they will be simple.',
    title: 'Dharma Bums',
    author: 'Jack Kerouac'
  },
  {
    id: '2',
    content: 'In the limits of a situation there is humor, there is grace, and everything else.',
    title: 'Arbitrary Stupid Goal',
    author: 'Tamara Shopsin'
  }
]

Queries

A query requests specific data from an API, in its desired format. The query will then return an object, containing the data that the API user has requested. A query never modifies the data; it only accesses it. We’ve already written a two queries in our schema. The first returns an array of highlights and the second returns a specific highlight. The next step is to write the resolvers that will return the data.

In the index.js file, we can add a resolvers object, which can contain our queries:

const resolvers = {
  Query: {
    highlights: () => highlights,
    highlight: (parent, args) => {
      return highlights.find(highlight => highlight.id === args.id);
    }
  }
};

The highlights query returns the full array of highlights data. The highlight query accepts two parameters: parent and args. The parent is the first parameter of any GraqhQL query in Apollo Server and provides a way of accessing the context of the query. The args parameter allows us to access the user provided arguments. In this case, users of the API will be supplying an id argument to access a specific highlight.

We can then update our Apollo Server configuration to include the resolvers:

const server = new ApolloServer({ typeDefs, resolvers });

With our query resolvers written and Apollo Server updated, we can now query API using the GraphQL Playground. To access the GraphQL Playground, visit http://localhost:4000 in your web browser.

A query is formatted as so:

query {
  queryName {
      field
      field
    }
}

With this in mind, we can write a query that requests the ID, content, title, and author for each our highlights:

query {
  highlights {
    id
    content
    title
    author
  }
}

Let’s say that we had a page in our UI that lists only the titles and authors of our highlighted texts. We wouldn’t need to retrieve the content for each of those highlights. Instead, we could write a query that only requests the data that we need:

query {
  highlights {
    title
    author
  }
}

We’ve also written a resolver to query for an individual note by including an ID parameter with our query. We can do so as follows:

query {
  highlight(id: "1") {
    content
  }
}

Mutations

We use a mutation when we want to modify the data in our API. In our highlight example, we will want to write a mutation to create a new highlight, one to update an existing highlight, and a third to delete a highlight. Similar to a query, a mutation is also expected to return a result in the form of an object, typically the end result of the performed action.

The first step to updating anything in GraphQL is to write the schema. We can include mutations in our schema, by adding a mutation type to our schema.js file:

type Mutation {
  newHighlight (content: String! title: String author: String): Highlight!
  updateHighlight(id: ID! content: String!): Highlight!
  deleteHighlight(id: ID!): Highlight!
}

Our newHighlight mutation will take the required value of content along with optional title and author values and return a Highlight. The updateHighlight mutation will require that a highlight id and content be passed as argument values and will return the updated Highlight. Finally, the deleteHighlight mutation will accept an ID argument, and will return the deleted Highlight.

With the schema updated to include mutations, we can now update the resolvers in our index.js file to perform these actions. Each mutation will update our highlights array of data.

const resolvers = {
  Query: {
    highlights: () => highlights,
    highlight: (parent, args) => {
      return highlights.find(highlight => highlight.id === args.id);
    }
  },
  Mutation: {
    newHighlight: (parent, args) => {
      const highlight = {
        id: String(highlights.length + 1),
        title: args.title || '',
        author: args.author || '',
        content: args.content
      };
      highlights.push(highlight);
      return highlight;
    },
    updateHighlight: (parent, args) => {
      const index = highlights.findIndex(highlight => highlight.id === args.id);
      const highlight = {
        id: args.id,
        content: args.content,
        author: highlights[index].author,
        title: highlights[index].title
      };
      highlights[index] = highlight;
      return highlight;
    },
    deleteHighlight: (parent, args) => {
      const deletedHighlight = highlights.find(
        highlight => highlight.id === args.id
      );
      highlights = highlights.filter(highlight => highlight.id !== args.id);
      return deletedHighlight;
    }
  }
};

With these mutations written, we can use the GraphQL Playground to practice mutating the data. The structure of a mutation is nearly identical to that of a query, specifying the name of the mutation, passing the argument values, and requesting specific data in return. Let’s start by adding a new highlight:

mutation {
  newHighlight(author: "Adam Scott" title: "JS Everywhere" content: "GraphQL is awesome") {
    id
    author
    title
    content
  }
}

We can then write mutations to update a highlight:

mutation {
  updateHighlight(id: "3" content: "GraphQL is rad") {
    id
    content
  }
}

And to delete a highlight:

mutation {
  deleteHighlight(id: "3") {
    id
  }
}

Wrapping up

Congratulations! You’ve now successfully built a GraphQL API, using Apollo Server, and can run GraphQL queries and mutations against an in-memory data object. We’ve established a solid foundation for exploring the world of GraphQL API development.

Here are some potential next steps to level up:

The post Get Started Building GraphQL APIs With Node appeared first on CSS-Tricks.