How to build a GraphQL API with Next.js and Vercel - Shadid Haque - (Next.js Conf 2021)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hey guys my name is Shadid and I love Next.js  I'm a developer advocate at Fauna the serverless   database and today I'm gonna show you guys how  to build a GraphQL API with Next.js and Vercel  Alright so why would you want to  build a GraphQL API with Next.js   suppose you have a React or Next.js application  and you're interacting with many small micro   services and third-party data sources so at this  point you might want to consider combining these   into a single GraphQL service doing so will reduce  complexity in your client-side code you can build   a GraphQL service inside your Next.js API layer  that way you don't have to create and maintain an   entirely new application your graphical code will  live in the same repository as your Next.js client   code making it easier to develop co-modules  and share code in between these two services   now finally when you deploy your Next.js  application to Vercel it turns your GraphQL   API into a serverless function now that is  powerful you don't have to deal with scaling   your application and it will auto scale you don't  really have to care about maintaining servers for   your GraphQL API it will be completely serverless  so that's interesting all right so we're going to   build on a simple GraphQL API using Next.js and  Vercel so stay tuned and let's jump into the   code all right so here we are in our terminal and  the first thing we are going to do is to create   our new Next.js application so I'm just going  to use create-next-app so npx create-next-app   and my app name I'm just gonna call it myapp and wait for it to scaffold our application Alright so it's it's working okay perfect now we can cd into our  application and open it up on VSCode all right so what we're going to do  is we're going to put our GraphQL   into the API layer so we're going to  create a new file here called GraphQL.js alright before we can write any code we  need to install a couple dependencies   so let's jump back to our terminal and  we're gonna install our dependencies so "npm i apollo -server-micro micro" course save   and we're installing the latest  version of Apollo Server  Micro so this is going to install the new Apollo  Server the Apollo 3. all right so let's jump back so the first thing we're gonna do is we're  gonna import our dependencies so let's import CORS from micro-cors and then import gql and ApolloServer from  apollo-server-micro all right so next we can create our typedef actually so let's create  our typedef so type that's equals gql oops and here okay so let's do some simple  GraphQL model so I'm just gonna call it   I'm just gonna call I'm just gonna make  a type called book so book will have   a title and a book also has an author property   and then I'm just going to create a  simple type to query all the books books and book returns an array of it's a books  return ray of book all right so that's our typedef   so next let's create a resolver  for this okay so resolvers and here query and then books and we can okay so we have to return something all right so  let's so let's create a static array since we're   not we're not connected to a database so we're  just gonna create an array with some objects okay so title uh what are some good books I'm just gonna  use the the one they have in Apollo website just some random books all right and  title for the next book city of glass all right author okay awesome and let's just oops return  books okay perfect all right so we got we got that figured out we got our resolver  oh okay so let's also do our course yeah I'm not really using semicolons and this one  all right okay so next let's create our Apollo   server and we're gonna make a new ApolloServer and  put our type defs right there and we're going to   put our resolvers right there we can do a context  let's do a contacts and contact is just a function and well we're not returning anything but  let's just do it anyways and then we're gonna   have introspection true and you can  also enable the playground so playground true all right okay all right so next what we can do   we're gonna have our servers to start so  we're just gonna start I can't spell today   server dot start so we're defining a variable  and we're putting the start function in there   now we're gonna see why we need to do  that it's because we need we need to wrap   our Apollo server to course and that's like  the only way to make the polysover micro   an Apollo 3 to work with next all right so we  can do export default and wrap our we're going to   wrap the whole export into the course function and  that's why we bought in course at the micro course   all right so here we can create a async function and it takes a request and a  response just like a normal   just like a normal Next.js API layer function  handler API tabular and then what we can do   we can check if the request method  is equals equals option or not because we only want to process post requests  technically so if it is then end the request here return false if not move on and then await  the Apollo server to start oh I don't think we need yeah since we already  defined it like that so we don't really need   to put the parentheses there and then await  apolloServer.create handler right there and let's put our path and this path has to  match your API path so we're going to go   api/graphql and we return our  request requests and response object   and that's about it all right let's save  it and let's try to run our application   back in the terminal let's try to  run our application with npm run dev okay now let's visit in our browser  so we're gonna go to api/graphql aha   so looks like it's working so let's try to  query our server and there is an error all   right so let's try to figure out what went  wrong and looks like we forgot to turn off   we forgot to turn off the body parser from  Next since we're using since we're using   Apollo server micro we don't need the body  parser so body parser and false set it to false all right so we run the  application and let's go back here   and okay now it's working okay so books title  author let's run it and it's running it's working all right okay so we're back here in our code so the next  thing we're going to do is we're going to connect   to a database and pull the book data from our  database to do so we're going to use our favorite   database Fauna okay so let's hop back into my  browser here and we're gonna go to fauna.com   and to get started it's it's completely free  to get started you know you just have to sign   up for an account and you don't really need a  credit card so it's it's super simple so I'm   just going to log into my Fauna dashboard  and I am going to create a new database   all right so we gotta give our database a  name I'm just gonna call it book store 2   because I already created a bookstore  earlier all right and then you can select   the region group and this specifies where your  data is located so I'm gonna I'm gonna say classic   and create and there you have it so this is  our our database and here we can create a new   collection so the collections are like the tables  if you're if you're coming for a SQL background   a collection is a table yeah so  let's create a table called book   collection called book and hit  save all right and a new book   collection is created now we can add document to  our collection and as you can see it's really easy   to insert document it just uses javascript syntax  so we can pretty much just copy these things and save them and they'll show  up let's create the other one save there you go we got both of our documents  and there okay so next thing what we have to   do we have to install the Fauna DB driver so  let's install that I can get rid of this save it   go back to my terminal install save and  let's wait for this to get installed okay so we got our driver installed now  what we need to do is we have to generate   a new Fauna secret so that our client application  our Next.js application can connect to our Fauna   database all right so let's go ahead and do that  okay so I'm just going to go back to my browser   and in my Fauna dashboard here in my bookstore  to database we're gonna select security and here   I'm gonna select new key and I'm gonna generate an  admin level key now in production you should never   generate an admin level key you should only use an  admin key in your pipeline in your ci cd pipeline   so you can you can take a look at the Fauna blogs  for for some of the best practices that we have   around authentication keys and securities  and so on and so forth however for this   there's a funnel blog right there okay so you  can check this out check this blog site out for   best practices and whatnot however for this demo  application we're just gonna use the admin role   okay so let's generate a key let's name our key  next app and I'm gonna hit save and a new key   is generated so I'm just gonna copy this go back  to my code over here and here we're gonna create   a couple new environment variables so we're gonna  create a dot env file and I'm gonna call it Fauna   secret and copy paste that also for our local  environment we can create another one env.local copy paste that there all right   okay so let's hop back into our graphql.js file  now what we are going to do is we are going to   create a new client for our Fauna so we're going  to create a new client to connect to the fonda   database and query some data from there to do  so we first need to import the client from Fauna and then we create a new client  so we just create const client new   client and here we have  we're going to have to pass   in the secret and this is the secret that  we just created so process.env.fauna_secret and the domain at the domain can be db.fauna.com there you go and now using the client we are  going to query the database now here in our   resolver we can just get rid of this go to async  function there you go all right okay so const   response we're gonna say await client dot query  and inside this query function we put our query to interact with Fauna we use a query language  called Fauna query language or fql in short   it is very similar to javascript and based  on a functional programming paradigm it   allows for complex precise manipulation  and retrieval of data stored within Fauna   okay so let's take a look at how we can use  FQL to query our database by the way if you   want to learn more about FQL just visit  the official documentation site for Fauna   and a good place to start learning FQL would be  the FQL cheat sheet so take a look at that as well okay so back here in the code and I  just realized there is a typo in here so   it's not going to be Fauna db  it's just going to be Fauna   all right so let's fix that all right so back  here and the query let's write our Fauna FQL query   so I'm gonna use a map function and bring in this  map function all right so a map function in Fauna   is very similar to a javascript map function  the type of map function you use to simplify   your arrays all right so within the map function  we're gonna use the paginate function so this will   paginate the list of documents that we get back  from Fauna and then we're gonna use documents   and I'm gonna use the documents  function from the library and collection and name of the collection okay so  let's bring in the collection here   as well right okay looking good and then  finally we're gonna use a lambda function   and by the way lambdas are similar lambdas  are pretty much like the arrow functions in   FQL and we're going to use the  lambda function just to define   just to define like whatever we're getting back  from the paginate function and to return it   and we also use a get function to get the data  from there all right so let's console.log this okay so this here is pretty much your FQL query   okay all right so let's test this out so  let's go back to our browser let's query this and return null and we can see that our  console log it is returning some data   so let's map this data and return them  as an array okay so here what I can do let's define a new variable and response.data.map item and we are going to get the  item dot data back okay and return and return the yeah box don't really need that we  don't also need this anymore so let's save   and try it here and there you go now we're  getting the data from the database awesome   okay so next let's deploy our application okay now let's go ahead and deploy our application  and the easiest way to deploy the application   is to Vercel CLI so I'm going to say I'm going  to npx vercel --prod it's going to go to prod   and depending on your internet speed it's gonna  take a few few minutes or a few seconds all right deploying you're gonna get a URL so I can  just go to the url it's done so I can go   API GraphQL it takes me back here okay so I can  just copy this url come back to Apollo Studio   and run a quarry just to test everything is  working and there you go everything is working   as expected now I can also go to vercel.com and  I can kind of take a look at my logs and if we   go to function logs and this is our GraphQL  API it turned it into a serverless function Hey I hope you enjoyed that video if you  have any feedback or if you just want to   say hi feel free to do so my social media  links should be in the description below and   other than that I will see you  next time and have a good day!
Info
Channel: Vercel
Views: 1,721
Rating: undefined out of 5
Keywords:
Id: UdvojvYnAhs
Channel Id: undefined
Length: 25min 15sec (1515 seconds)
Published: Wed Oct 27 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.