Deploying Basic ServerLess React App with Hasura GraphQL Engine

Himanshu Dixit
9 min readDec 15, 2018

--

Today most of the legacy backend systems are based on the REST(REpresentational State Transfer), but from the last 2–3 years “Graph QL” AKA replacement for REST, a new way to serve data is getting popular. So what is it, why to use it and how to use it, we will discuss all about GrapQL .

What is Graph QL?

GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data.

It was developed by Facebook in 2012 when their apps started getting complex, a solution to the problem was to build a different REST API for mobile apps or do handling at multiple places in a rest service. So they went ahead with a new way to define, insert and request the data.

In GraphQL, a query is a string that is sent to a server to be interpreted and fulfilled, which then returns JSON back to the client.

Facebook open sourced it in 2015 under the MIT license.

Why Use Graph QL?

Graph QL is a query language developed by Facebook in 2012, and they open sourced it in 2015 under the MIT license.

Multiple Version — In large codebase, it becomes a hectic and frustrating task to manage different versions of API for different platforms or support.

Over Fetching — Under Fetching — Most of the time in client applications, we don’t require all the data that we get from one endpoint, which results in performance issue if the data fetched is too large and is frequently accessed.

Less no. of requests — Instead of making multiple requests to the server, with the help of GraphQL different type of data can be served in one go.

What is Hasura?

Hasura is PAAS startup, which allows developer and enterprise to quickly build, test and deploy their application in a secure and cost-efficient way.
One of the offerings of Hasura is Graph Ql engine, which is very lightweight in nature and can handle up to 1,000 Queries/second on Heroku free tier platforms.

Hasura gives you instant realtime GraphQL APIs over any Postgres database without having to write any backend code. It can be deployed on Heroku and Digitalocean in just a few minutes.

Creating a complete To-Do App powered by GraphQL

We will be building a simple note-taking app that allow users to log in, create a list of to-do tasks and then perform actions over them. In short, a complete CRUD (Create, Reade, Update, Delete) application with user authentication.

Final demo of the app can be seen here :- https://deploy-to-hasura.herokuapp.com

In the following project will be using two primary services

Getting our hands dirty

For the frontend side, we’re using React, another open source software framework by Facebook. We’ll be using React-CLI (command line interface) to generate boilerplate code.

Setting up a basic demo project, we can set up the basic project using the following steps.

Installing Node

In Ubuntu

sudo apt update
sudo apt-get install nodejs

In MacOS

brew install node

Installing Yarn

Although you can use NPM also, yarn in much faster in installing libraries when compared to NPM.

In Ubuntu

sudo apt update
sudo apt install yarn

In MacOS

brew install yarn

Installing Create-react-native

yarn global add create-react-app

Now we can start developing on react by running the following

yarn create react-app todo-app

Now we will have a basic boilerplate react project, with following project structure.

todo-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
└── serviceWorker.js

We can start running our react app with

yarn run start

If everything goes well, then we can access our app at http://localhost:3000

NOTE: If there’s already service running on port 3000, then react will start app on another port.

We’ll have 3 main routes in our todo app

  1. ) Login Page — We’ll give an option for a user to login using auth0 service.
  2. ) Callback — This route will be a response for handling the callback response from Auth0.
  3. ) Dashboard — This will the main component of our app, here a user can perform add, complete task and delete task option.

To structure our project better, we will create different react components for Login and Dashboard page.

todo-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├──pages
├──Dashboard
├──Dashboard.js
├──Login
├──Login.js
├── logo.svg
├── services
├──history.js
└── serviceWorker.js

Our basic component for Dashboard and Login will be in this form

Now, we will use react-router to define a different route. We can install react router by using the following command.

yarn add react-router-dom

And now we should define our routes in App.js

We need to also pass browser history to the router in App.js, we should create a file services/history.js

At this point, our app looks something like this. Feel free to add your own CSS to give the app a different look.

Using Auth0 as authentication service

We need to add user authentication when a user clicks on the login button, we can add it by following

  1. ) Registering Single page application on https://manage.auth0.com/. Note down your domain and client id
  2. ) Defining Callback URL in app settings page. In our case, it will be http://localhost:3000/callback
  3. ) Run yarn add auth0-js
  4. ) Now will define service/Auth.js to handle all the logic related to user management.

4.) Now we should add click event on login button.

5.) Also, we need to define logic to handle the callback that we receive from Auth0 after user authentication.

We have also added logic to redirect the user to /dashboard if he’s already logged in.

Getting started with Hasura GraphQL Engine on Heroku

1.) Go to Hasura.io, click on Deploy to Heroku. You can also deploy the app to digitalocean.

2.) Now run your Heroku app.

3.) Click on the data tab and create a table with following schema.

4.) Insert few records to todo table.

5.) Now we can run sample queries on our Graph QL engine.

Query to extract id, task, user and completed from the table todo

query {
todo{
id
task
user
completed
}
}

GraphQL Mutation : GraphQL mutation can perform Insert, Update and Delete operation on table.

To insert a record in the todo app

mutation {
insert_todo(
objects: [
{
task: "Complete react app",
user: "himanshu"
}
]
){
affected_rows
}
}

To delete a record in the todo app

mutation {
delete_todo(
where: {id: {_eq:1}}
){
affected_rows
}
}

To update a record in the todo app

mutation {
update_todo(
where: {id: {_eq:1}}
_set: {completed: true}
){
affected_rows
}
}

Setting Roles on the table

We can now perform operations on our GraphQL engine, the only problem is that we have not restricted it according to a user role. So at this point, anyone can perform any operation the database.

Now, we’ll add new permission role to our todo table.

Now save the permission, make sure to apply them over the insert, select, update and delete.

Run the above query again with the following parameters, now the data of the only user with user-id will be displayed. More information about this can be found at https://docs.hasura.io/1.0/graphql/manual/auth/roles-variables.html

Setting Auth0 webhook with Hasura

In our app, we’ll be using Access token retrieved from Auth0 to perform an action on the GraphQL engine. To enable this, we need to establish Webhook for Auth0 in our Hasura App, we’ll send the token to this webhook URL to retrieve the User-Id and perform actions.

  1. ) Click Quick Deploy to Heroku on, https://github.com/hasura/sample-auth-webhook.
  2. Set AUTH_ZERO_DOMAIN environment variable in heroku app. You can get this domain from auth0 console.

3. Now our webhook is successfully running at

https://<heroku-url>/auth0/webhook

4. Now go to your Hasura Heroku app, and set HASURA_GRAPHQL_ACCESS_KEY tand HASURA_GRAPHQL_AUTH_HOOK

We have successfully setup Auth0 Webhook with our Hasura app :)

Yo can also use Auth0 integration thru JWT, Auth0 JWT Integration with Hasura GraphQL engine

Integrating GraphQL with our React App

To integrate Graph QL to our app we’ll be use Apollo to perform an operation on Graph QL server. We’ll be using react-apollo, which is a react integration for apollo client.

yarn add apollo-boost react-apollo graphql 

There will basically be 4 operations that’ll be performing in our app

  1. ) Fetching all the tasks from GraphQL server.
  2. ) Adding a todo to the database.
  3. ) Deleting a todo from a database based on id.
  4. ) Marking a todo completed in our app.

For the following operations, we’ll define GraphQL template. We’ll keep in in a separated file for modularity purpose.

Making our Dashboard Functional

  1. ) We’ll create new Apollo client in the constructor. We’ll use the Access token we get from Auth0 to perform actions on Hasura GraphQL server(Remember: We have already setup webhook with Hasura ;))
  2. )Pass the newly constructed Apollo Client to Apollo Provider to perform operations. We’ll use Access token we get from Auth0.

Now, we’ll create different componenst that will be placed in ApolloProvider :- ListAllToDos, DeleteToDo, UpdateToDo, AddToDo.

ListAllToDo.js

Here we’ll be executing getTodos query and then iterate to list all the tasks.

AddToDo.js

We’ll be executing the mutation defined in Query.js . After inserting the query, we’ll be refetching the queries to display the changes.

DeleteToDo.js

After deleting the query, we’ll be refetching the queries to display the changes.

UpdateToDo.js

Now We have a basic functional app running, we’ll add logout functionality in Dashboards.js

The source code of the project can be found at

Deploying our React App

Now we have completed our basic ToDo app, we need to do two things

  1. ) Deploy app on Heroku

Add heroku-postbuild in package.json, this will automatically build the react app when we push the app to heroku server.

"scripts": {
...
"heroku-postbuild": "npm run build"
}

Now push the code to heroku app.

2. ) Update callback URL in Auth0 console

In Auth0 console, change the callback url from http://localhoost:3000/callback to http://<heroku app url>/callback

Yay, we have succesfully deployed our app. Now try to open the app in browser and test it out.

Demo of the app :- https://deploy-to-hasura.herokuapp.com/

Source code :- https://github.com/himanshu-dixit/React-GraphQL-ToDo-App

About Me

I am founder at Sveet, Project Leader At Oppia, and Core Developer at Drupal. I have also been Google Summer of Code’17 Student & Google Code In Mentor.
You can follow me on Twitter @himanshu_dix, Quora and GitHub @himanshu-dixit.

--

--

Himanshu Dixit

Creator @ http://prepstart.co ✨✨Polyglot eng👨‍💻👨‍💻 UI designer 😍😍 Product ❤️❤️, like to solve my problems. Hit me up for — Eng, Design, Product.