End to End React with Prisma 2

Start at the beginning and work your way through this project. The code for each step as well as the finished project can be found in the Github repository.

    4. Add graphQL server

    Objective: Let's add the main api that our frontend will use for fetching and sending all its data.

    npm install --save micro-cors apollo-server-micro graphql-tools graphql-middleware graphql-shield lodash

    Here, the main package we use is graphql-server-micro. It is a micro version of the apollo server which will keep it as minimalistic as possible since the server will be run out of lambda function using the Next.js api. Let's start by creating the graphQL server. Create the following file:



    import { ApolloServer } from 'apollo-server-micro'
    import Cors from 'micro-cors'
    const cors = Cors()
    export const config = {
    api: {
    bodyParser: false,
    const handler = new ApolloServer({
    path: '/api/graphql',
    export default cors((req, res) => {
    if (req.method === 'OPTIONS') {
    return res.status(200).send()
    } else {
    return handler(req, res)

    The micro-cors is a package that will allow us to handle a problem that we will encounter with our frontend. The problem is that the frontend sends a OPTIONS request when it connects to understand which types of requests are allowed by the backend server. We can use the cors method to look for OPTIONS calls and then selectively pass those automatically so they won't fail. All other requests will be sent to our handler which is the ApolloServer itself.

    You'll notice that we have not defined schema above, so let's do this now. We will create an executable schema by using the makeExecutableSchema method from the graphql-tools package. Define the following in the graphql.ts file right below where we define cors.



    // more code above
    const schema = applyMiddleware(
    makeExecutableSchema({ typeDefs, resolvers }),
    // more code below

    We will define the typeDefs and resolvers in two files by the same name in the utils/api folder.



    export const resolvers = {
    Query: {
    hello: (parent, args, context) => `hi!`,



    import { gql } from 'apollo-server-micro'
    export const typeDefs = gql`
    type Query {
    hello: String

    We are putting in a dummy query here that simply returns a string. Let's try it out by going to http://localhost:3000/api/graphql. It should bring up a graphQL ui. Try to run the following query:



    It should return the string hi!.