{"id":2319,"date":"2022-01-26T10:14:47","date_gmt":"2022-01-26T10:14:47","guid":{"rendered":"https:\/\/lvboard.infostore.in.ua\/?p=2319"},"modified":"2022-01-26T10:14:47","modified_gmt":"2022-01-26T10:14:47","slug":"how-to-build-a-graphql-server-using-next-js-api-routes","status":"publish","type":"post","link":"https:\/\/lvboard.infostore.in.ua\/?p=2319","title":{"rendered":"How To Build A GraphQL Server Using Next.js API Routes"},"content":{"rendered":"\n<p>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.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>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.<\/p>\n\n\n\n<p>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.<\/p>\n\n\n\n<p>So, let\u2019s dive in.<\/p>\n\n\n\n<h2 id=\"what-are-next-js-api-routes\">What Are Next.js API Routes?&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/10\/graphql-server-next-javascript-api-routes\/#what-are-next-js-api-routes\">#<\/a><\/h2>\n\n\n\n<p>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 <code>pages\/api<\/code> as API endpoints. Meaning that, now, you will be able to access your API endpoint on the URL <code>https:\/\/localhost:3000\/api\/your-file-name<\/code>.<\/p>\n\n\n\n<p>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?<\/p>\n\n\n\n<p>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\u2019s technically a React framework. Hopefully, you get it right.<\/p>\n\n\n\n<p>So far, we have learned what API Routes are. However, the real question remains: <em>why use Next.js to build a GraphQL Server<\/em>? Why not use GraphQL or Node.js to do so? So, let\u2019s compare Next.js API Routes to existing solutions for building APIs in the next section.<\/p>\n\n\n\n<h2 id=\"next-js-api-routes-versus-rest-and-graphql\">Next.js API Routes Versus REST And GraphQL&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/10\/graphql-server-next-javascript-api-routes\/#next-js-api-routes-versus-rest-and-graphql\">#<\/a><\/h2>\n\n\n\n<p>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.<\/p>\n\n\n\n<p>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\u2019s a React framework that enables you to add a backend to it in no-time.<\/p>\n\n\n\n<p>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 <code>https:\/\/localhost:3000\/api\/your-file-name<\/code>. The API Routes won\u2019t increase your client-side bundle size because they are server-side only bundles.<\/p>\n\n\n\n<p>However, Next.js API Routes are only accessible within the same-origin because API Routes do not specify <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTTP\/CORS\">Cross-Origin Resource Sharing (CORS)<\/a> headers. You can still tweak the default behavior by adding CORS to your API \u2014 but it\u2019s an extra setup. If you generate your Next App statically using <code>next export<\/code> \u2014 you won\u2019t be able to use API Routes within your app.<\/p>\n\n\n\n<p>So far, we have learned when API Routes might be a better solution compared to the like. Now, let\u2019s get hands dirty and start building our GraphQL Server. More after jump! Continue reading below&nbsp;\u2193<\/p>\n\n\n\n<p>Meet <strong><a href=\"https:\/\/www.smashingmagazine.com\/printed-books\/touch-design-for-mobile-interfaces\/\">\u201cTouch Design for Mobile Interfaces\u201d<\/a><\/strong>, our <strong>brand-new Smashing Book<\/strong> on designing for mobile with proven, universal, human-centric guidelines. 400 pages, jam-packed with <strong>in-depth user research and guidelines<\/strong> you can apply immediately. Shipping starts early January 2022.<a href=\"https:\/\/www.smashingmagazine.com\/printed-books\/touch-design-for-mobile-interfaces\/\">Jump to table of contents&nbsp;\u21ac<\/a><a href=\"https:\/\/www.smashingmagazine.com\/printed-books\/touch-design-for-mobile-interfaces\/\"><\/a><\/p>\n\n\n\n<h2 id=\"setting-up\">Setting Up&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/10\/graphql-server-next-javascript-api-routes\/#setting-up\">#<\/a><\/h2>\n\n\n\n<p>To start a new app with Next.js, we will go for Create Next App. It\u2019s 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:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npx create-next-app next-graphql-server<\/code><\/pre>\n\n\n\n<p>Next.js provides a starter template for API Routes. You can use it by executing the following command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npx create-next-app --example api-routes api-routes-app<\/code><\/pre>\n\n\n\n<p>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:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\u251c\u2500\u2500 pages\n|  \u251c\u2500\u2500 api\n|  |  \u251c\u2500\u2500 graphql.js\n|  |  \u251c\u2500\u2500 resolvers\n|  |  |  \u2514\u2500\u2500 index.js\n|  |  \u2514\u2500\u2500 schemas\n|  |     \u2514\u2500\u2500 index.js\n|  \u2514\u2500\u2500 index.js\n\u251c\u2500\u2500 package.json\n\u2514\u2500\u2500 yarn.lock\n<\/code><\/pre>\n\n\n\n<p>As we said earlier, the <code>api<\/code> 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 <code>\/api\/graphql<\/code>, which is the entry point of the GraphQL server.<\/p>\n\n\n\n<p>With this step forward, we can now create the GraphQL Schema for our server.<\/p>\n\n\n\n<h2 id=\"create-the-graphql-schemas\">Create The GraphQL Schemas&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/10\/graphql-server-next-javascript-api-routes\/#create-the-graphql-schemas\">#<\/a><\/h2>\n\n\n\n<p>As a quick recap, a GraphQL schema defines the shape of your data graph.<\/p>\n\n\n\n<p>Next, we need to install <code>apollo-server-micro<\/code> to use Apollo Server within Next.js.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>yarn add apollo-server-micro<\/code><\/pre>\n\n\n\n<p>For <code>npm<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm install apollo-server-micro<\/code><\/pre>\n\n\n\n<p>Now, let\u2019s create a new GraphQL schema.<\/p>\n\n\n\n<p>In <code>api\/schemas\/index.js<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import  {  gql  }  from  \"apollo-server-micro\"; \n\nexport  const  typeDefs  =  gql`\n    type  User {\n        id: ID\n        login: String\n        avatar_url: String\n    }\n\n    type  Query {\n        getUsers: &#91;User]\n        getUser(name: String!): User!\n    }`<\/code><\/pre>\n\n\n\n<p>Here, we define a <code>User<\/code> type that describes the shape of a Github user. It expects an <code>id<\/code> of type <code>ID<\/code>, a <code>login<\/code>, and an <code>avatar_url<\/code> of type String. Then, we use the type on the <code>getUsers<\/code> query that has to return an array of users. Next, we rely on the <code>getUser<\/code> query to fetch a single user. It needs to receive the name of the user in order to retrieve it.<\/p>\n\n\n\n<p>With this GraphQL Schema created, we can now update the resolver file and create the functions to perform these queries above.<\/p>\n\n\n\n<h2 id=\"create-the-graphql-resolvers\">Create The GraphQL Resolvers&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/10\/graphql-server-next-javascript-api-routes\/#create-the-graphql-resolvers\">#<\/a><\/h2>\n\n\n\n<p>A GraphQL resolver is a set of functions that allows you to generate a response from a GraphQL query.<\/p>\n\n\n\n<p>To request data from the Github API, we need to install the <code>axios<\/code> library. So, open your CLI and execute this command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>yarn add axios<\/code><\/pre>\n\n\n\n<p>Or when using <code>npm<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm install axios<\/code><\/pre>\n\n\n\n<p>Once the library is installed, let\u2019s now add some meaningful code to the resolvers file.<\/p>\n\n\n\n<p>In <code>api\/resolvers\/index.js<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import axios from \"axios\";\n\nexport const resolvers = {\n  Query: {\n    getUsers: async () =&gt; {\n      try {\n        const users = await axios.get(\"https:\/\/api.github.com\/users\");\n        return users.data.map(({ id, login, avatar_url }) =&gt; ({\n          id,\n          login,\n          avatar_url\n        }));\n      } catch (error) {\n        throw error;\n      }\n    },\n    getUser: async (_, args) =&gt; {\n      try {\n        const user = await axios.get(\n          `https:\/\/api.github.com\/users\/${args.name}`\n        );\n        return {\n          id: user.data.id,\n          login: user.data.login,\n          avatar_url: user.data.avatar_url\n        };\n      } catch (error) {\n        throw error;\n      }\n    }\n  }\n};<\/code><\/pre>\n\n\n\n<p>As you can see here, we match the queries name defined earlier on the GraphQL Schema with the resolver functions. The <code>getUsers<\/code> function enables us to retrieve all users from the API and then return an array of users that needs to mirror the <code>User<\/code> type. Next, we use the <code>getUser<\/code> method to fetch a single user with the help of the name passed in as a parameter.<\/p>\n\n\n\n<p>With this in place, we now have a GraphQL Schema and a GraphQL resolver \u2014 it\u2019s time to combine them and build up the GraphQL Server.<\/p>\n\n\n\n<h2 id=\"create-the-graphql-server\">Create The GraphQL server&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/10\/graphql-server-next-javascript-api-routes\/#create-the-graphql-server\">#<\/a><\/h2>\n\n\n\n<p>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.<\/p>\n\n\n\n<p>In <code>api\/graphql.js<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import  {  ApolloServer  }  from  \"apollo-server-micro\";\nimport  {  typeDefs  }  from  \".\/schemas\";\nimport  {  resolvers  }  from  \".\/resolvers\";\n\nconst  apolloServer  =  new  ApolloServer({  typeDefs,  resolvers  });\n\nexport  const  config  =  {\n    api:  {\n        bodyParser:  false\n    }\n};\n\nexport  default  apolloServer.createHandler({ path:  \"\/api\/graphql\"  });<\/code><\/pre>\n\n\n\n<p>After importing <code>ApolloServer<\/code>, 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 <code>apolloServer<\/code> to create a new handler, which means the path <code>\/api\/graphql<\/code> will serve as an entry point for our GraphQL server.<\/p>\n\n\n\n<p>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\u2019t have to start the GraphQL server on our own.<\/p>\n\n\n\n<p>Great! With this step forward, we can now test if the GraphQL server works.<\/p>\n\n\n\n<h2 id=\"test-the-graphql-server\">Test The GraphQL Server&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/10\/graphql-server-next-javascript-api-routes\/#test-the-graphql-server\">#<\/a><\/h2>\n\n\n\n<p>Once you browse to the root of the project, open it on the CLI, and then execute this command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>yarn dev<\/code><\/pre>\n\n\n\n<p>Or for <code>npm<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm run dev<\/code><\/pre>\n\n\n\n<p>Now, visit <code>https:\/\/localhost:3000\/api\/graphql<\/code> and add the GraphQL query below to retrieve all users from Github.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  getUsers {\n    id\n    login\n    avatar_url\n  }\n}<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"https:\/\/cloud.netlifyusercontent.com\/assets\/344dbf88-fdf9-42bb-adb4-46f01eedd629\/8b8ef082-8f9f-4491-a7e3-a5a53358d89a\/1-graphql-server-next-js-api-routes.PNG\"><img src=\"https:\/\/res.cloudinary.com\/indysigner\/image\/fetch\/f_auto,q_80\/w_400\/https:\/\/cloud.netlifyusercontent.com\/assets\/344dbf88-fdf9-42bb-adb4-46f01eedd629\/8b8ef082-8f9f-4491-a7e3-a5a53358d89a\/1-graphql-server-next-js-api-routes.PNG\" alt=\"get-all-users\"\/><\/a><figcaption>get-all-users. (<a href=\"https:\/\/cloud.netlifyusercontent.com\/assets\/344dbf88-fdf9-42bb-adb4-46f01eedd629\/8b8ef082-8f9f-4491-a7e3-a5a53358d89a\/1-graphql-server-next-js-api-routes.PNG\">Large preview<\/a>)<\/figcaption><\/figure>\n\n\n\n<p>Let\u2019s check if we can fetch a single user with this query.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>query($name: String!){\n  getUser(name:$name){\n        login\n    id\n    avatar_url\n  }\n}<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"https:\/\/cloud.netlifyusercontent.com\/assets\/344dbf88-fdf9-42bb-adb4-46f01eedd629\/61e2bea4-5a2f-47b5-9b60-5f86a7b9b65f\/2-graphql-server-next-js-api-routes.PNG\"><img src=\"https:\/\/res.cloudinary.com\/indysigner\/image\/fetch\/f_auto,q_80\/w_400\/https:\/\/cloud.netlifyusercontent.com\/assets\/344dbf88-fdf9-42bb-adb4-46f01eedd629\/61e2bea4-5a2f-47b5-9b60-5f86a7b9b65f\/2-graphql-server-next-js-api-routes.PNG\" alt=\"get-user\"\/><\/a><figcaption>get-user. (<a href=\"https:\/\/cloud.netlifyusercontent.com\/assets\/344dbf88-fdf9-42bb-adb4-46f01eedd629\/61e2bea4-5a2f-47b5-9b60-5f86a7b9b65f\/2-graphql-server-next-js-api-routes.PNG\">Large preview<\/a>)<\/figcaption><\/figure>\n\n\n\n<p>Great! Our server works as expected. We are done building a GraphQL server using Next.js API Routes.<\/p>\n\n\n\n<h2 id=\"conclusion\">Conclusion&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/10\/graphql-server-next-javascript-api-routes\/#conclusion\">#<\/a><\/h2>\n\n\n\n<p>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.<\/p>\n\n\n\n<p>You can preview the <a href=\"https:\/\/9y1ut.sse.codesandbox.io\/api\/graphql\">finished project on CodeSandbox<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[30],"tags":[194,161],"_links":{"self":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2319"}],"collection":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2319"}],"version-history":[{"count":1,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2319\/revisions"}],"predecessor-version":[{"id":2320,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2319\/revisions\/2320"}],"wp:attachment":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2319"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2319"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2319"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}