JavaScript

How to Deploy GraphQL Application Using Node.js on EC2 Server

GraphQL, also known as Graph Query Language, established and maintained by Facebook, is a query language used for APIs. It is built using JavaScript, Scala, Java, and Ruby programming languages. Its basic purpose is to ask for the data from server to client.GraphQL aggregates the data from different sources. Aggregation is the process of filtering data on the server side and then sending the filtered data to the client. Without aggregation, we send all the data to the client, and then the data is filtered at the client-side. This makes the system slow, and we can improve the efficiency of an API by using GraphQL. Here we will learn to deploy a simple GraphQL application using node.js on an EC2 server.

Installing Required Packages

The first step to deploy your graphQL application is to ready your server by installing the required packages. Log in to the server using SSH.

ubuntu@ubuntu:~$ ssh ubuntu@IPAdress -i KeyPair.pem

NOTE: Make sure the security group of the instance is configured to allow connection from port 22 and the private key file has 400 permission.

Update Ubuntu repositories.

ubuntu@ubuntu:~$ sudo apt-get update -y

Now install node.js and npm on your ubuntu server.

ubuntu@ubuntu:~$ sudo apt-get install nodejs -y
ubuntu@ubuntu:~$ sudo apt-get install npm -y

Verify the installation by checking the version of node.js and npm.

ubuntu@ubuntu:~$ node -v
ubuntu@ubuntu:~$ npm -v

Move GraphQL Application to EC2 Server

The EC2 instance is ready to deploy graphQL applications in node.js. Now we will move our code to the EC2 instance. Two common ways to copy the code to the server are listed below and will be discussed here.

  • Copy code using scp command
  • Clone application code from Github, Gitlab, or Bitbucket

Copy Application Using scp Command

In order to copy your application to the EC2 server using the scp command, First of all, remove the ā€˜node_modulesā€™ directory from your graphQL application. This directory has all the npm packages required to run the application. We will install these packages later before starting the graphQL application. Now compress the project directory into a zip file. After creating the zip file, we will move the project zip file to the server. Linux and windows have different methods to create a zip file.

Windows

In windows, right-click on the application root directory and go to the ā€˜send toā€™ option. It will open a submenu. Click on the ā€˜Compressed (zipped) folderā€™ to create a zip file of the graphQL application.

Linux or Mac

In Linux or Mac OS, we will use the ā€˜zipā€™ command to create a zip file of the project.

ubuntu@ubuntu:~$ zip -r graphQL.zip graphQL

The above command will generate the graphQL.zip file of the graphQL directory.

Upload Application to the Server

Now we have a zip file of our application, and we can upload the zip file to the server by using the scp command.

ubuntu@ubuntu:~$ scp -i KeyPair.pem graphQL.zip ubuntu@IPAddress:~/

The above command will move the project zip file to the remote serverā€™s home directory over the ssh connection. Now on the remote server, unzip the project zip file.

ubuntu@ubuntu:~$ unzip graphQL.zip

Clone Application From Github, Bitbucket or Gitlab

The second method to copy application code to the server is using git. Install git from the command line on the EC2 server.

ubuntu@ubuntu:~$ sudo apt install git

Check the git version to verify the installation.

ubuntu@ubuntu:~$ git --version

If it does not give the version of git, then git is not installed. Now clone the application from the github, gitlab, or bitbucket. Here we will clone the application code from the github.

ubuntu@ubuntu:~$ git clone ttps://github.com/contentful/the-example-app.nodejs

Starting the GraphQL Application

Now we have our graphQL application on the remote server. Go to the root directory of the graphQL application and install the required npm packages to run the graphQL application.

ubuntu@ubuntu:~$ cd graphQL
ubuntu@ubuntu:~$ sudo npm install

This command will analyze the package.json file in the project and install all the required npm packages. After installing the required packages, now we will start the graphQL application.

ubuntu@ubuntu:~$ node app.js

Running Application as Daemon

When we run the application using the standard method as described above, it runs in the foreground, and the application stops when you close the terminal window. We can run the application as a background process by appending the ampersand (&) sign to the command.

ubuntu@ubuntu:~$ node app.js &

The problem with this method is that when we modify our application code, the applied changes will not reflect automatically. We will have to restart the application every time we modify the code to apply the changes. In order to run the application in the background and to apply changes automatically, we will use an npm package named pm2. Install pm2 on the server.

ubuntu@ubuntu:~$ sudo npm install -g pm2

Start the graphQL application using pm2.

ubuntu@ubuntu:~$ pm2 start app.js --name ā€œgraphQLā€ --watch

The ā€˜–nameā€™ flag will name the background process, and we can start and stop the application using the name. The ā€˜–watchā€™ flag will go on checking the application code to apply changes immediately. You can learn more about pm2 by visiting the following link

https://pm2.keymetrics.io/

Querying GraphQL API from Browser

We can configure our graphQL application to make graphQL queries from the browser manually. For this, we have to create a separate HTTP endpoint on which we will mount the graphQL API server. And this HTTP endpoint will be used to make manual queries. Following is the code to create the graphQL api server endpoint.

const express = require(ā€˜expressā€™);
const { graphqlHTTP } = require(ā€˜express-graphqlā€™);
const { buildSchema } = require(ā€˜graphqlā€™);

const graphQLSchema = buildSchema(`
    type Query{
    message: String
    }`
);

const func = {
    message: () =>
    {
        return ā€˜you are using graphql api serverā€™;
    }
};

const server = express();
server.use(ā€˜/graphqlā€™, graphqlHTTP({
    schema: graphQLSchema,
    rootValue: func,
    graphiql: true
}));

server.listen(3000);

Now, after running the server, we can access the graphQL api server on the following route.

http://localhost:3000/graphql

Querying GraphQL API Using CLI

In the previous section, we made graphQL queries from the browser using graphiql. Now we are going to make graphQL queries using the command-line interface in ubuntu. From the command line, to make an HTTP POST request, we will use the curl module.

ubuntu@ubuntu:~$ curl -X POST -H "Content-Type: application/json" -d '{"query": "{ message }"}' http://localhost:3000/graphql

Querying GraphQL API Programmatically

In order to make graphQL query programmatically, we will use the ā€˜node-fetchā€™ module in node.js. Open node.js in the terminal.

ubuntu@ubuntu:~$ node

Now make the HTTP POST request to the server using the ā€˜node-fetchā€™ module.

GraphQL is an efficient query language, and it can decrease the response time of a query made to the database. The standard api calls to fetch data from the database involve many unuseful data in the response, and hence response time increases, which decreases the efficiency. The query made to the databases using GraphQL returns only the useful data and hence decreases the response time. In this article, we have deployed our graphQL application on an EC2 instance.

About the author

Usama Azad

A security enthusiast who loves Terminal and Open Source. My area of expertise is Python, Linux (Debian), Bash, Penetration testing, and Firewalls. Iā€™m born and raised in Wazirabad, Pakistan and currently doing Undergraduation from National University of Science and Technology (NUST). On Twitter i go by @UsamaAzad14