JavaScript GraphQL client requests in Node and the browser using `graphql.js`
Tags: graphql, javascript, webdev, node
Published: 2018-09-05 15:48:35

---
title: JavaScript GraphQL client requests in Node and the browser using `graphql.js`
published: true
tags: graphql, javascript, webdev, node
canonical_url: https://codewithhugo.com/javascript-graphql-client-requests-in-node-and-the-browser-using-graphql.js/
---

> An example consuming a GraphQL API in JavaScript from Node and the browser using `graphql.js`

See the example live: [https://codewithhugo.com/js-graphql-client-example/](https://codewithhugo.com/js-graphql-client-example/).

Full repo: [https://github.com/HugoDF/js-graphql-client-example](https://github.com/HugoDF/js-graphql-client-example).

- Fetching from Node
- Fetching from the browser
- GraphQL documentation tools

> This was sent out on the [Code with Hugo newsletter](https://buttondown.email/hugo) last Monday.
> [Subscribe](https://buttondown.email/hugo) to get the latest posts right in your inbox (before anyone else).

## Fetching from Node

`fetch.js`:

```js
const graphql = require('graphql.js');

const graph = graphql('https://graphql-pokemon.now.sh/');

const query = graph(`{
  pokemon(name: "Pikachu") {
    attacks {
      special {
        name
      }
    }
  }
}`);

if (require.main === module) {
  query().then(
    res => console.log(JSON.stringify(res, null, 2)),
    err => console.error(err)
  );
}

module.exports = {
  query
};
```


```sh

$ node fetch.js
{
  "pokemon": {
    "attacks": {
      "special": [
        {
          "name": "Discharge"
        },
        {
          "name": "Thunder"
        },
        {
          "name": "Thunderbolt"
        }
      ]
    }
  }
}
```

## Fetching from the browser

`graphql.js` is isomorphic, it’ll also run in the browser, we’ll use Parcel to stitch everything together.

By default we fetch using the query from `fetch.js`, then when the user clicks the `Try it` button we use the contents of the textarea.

This code wires up the fetch logic with some reading the query from the DOM and updating an output div on completion, `client.js`:

```js
const { query, graph } =require('./fetch');

const $queryElement = document.querySelector('.query');
const $output = document.querySelector('.output');
const $submitButton = document.querySelector('button');

$submitButton.onclick = () => {
  const queryData = $queryElement.value;
  runQuery(graph(queryData))
}

runQuery(query);

function runQuery (query) {
  query().then(
    res => {
      $output.innerHTML = `<pre><code>${JSON.stringify(res, null, 2)}</code></pre>`;
    },
    err => {
      $output.innerHTML = `Error: <pre><code>${JSON.stringify(err, null, 2)}</code></pre>`;
    }
  )
}

```

`index.html`:

```html
<!doctype html>
<html class="no-js" lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>JavaScript GraphQL Client Example</title>
  <meta name="description" content="JavaScript GraphQL Client example">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <style>
    body {
      font-family: -apple-system, BlinkMacSystemFont,
          'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell,
          'Open Sans', 'Helvetica Neue', sans-serif;
    }
  </style>
</head>

<body>
  <p>For full documentation see: <a href="https://graphql-pokemon.now.sh/">https://graphql-pokemon.now.sh/</a></p>
  <h2>Input: </h2>
  <textarea class="query" style="min-width: 285px; min-height: 150px">
{
  pokemon(name: "Pikachu") {
    attacks {
      special {
        name
      }
    }
  }
}
  </textarea>
  <button>Try it</button>
  <h2>Output: </h2>
  <div class="output"></div>
  <script src="./client.js"></script>
</body>

</html>
```


```sh
$ npm install --save-dev parcel

$ npx parcel index.html
```

Open [http://localhost:1234](http://localhost:1234).

![Sample GraphQL query result displayed in the browser](https://d2mxuefqeaa7sj.cloudfront.net/s_436CC3FB0186E19AFA848D5D9BBDDD002D6719E8B00591E0944C85836193A66D_1533923400947_image.png)

To test it out, we can change the textarea content to:

```gql
{
  pokemon(name: "Pikachu") {
    attacks {
      fast {
        name
        type
        damage
      }
      special {
        type
        damage
        name
      }
    }
  }
}
```

And click `Try it`. Which yields the following:

![new GraphQL query output in browser](https://d2mxuefqeaa7sj.cloudfront.net/s_436CC3FB0186E19AFA848D5D9BBDDD002D6719E8B00591E0944C85836193A66D_1534187747016_image.png)

## GraphQL documentation tools

For the hosted GraphQL docs of the pokemon GraphQL API, see [https://graphql-pokemon.now.sh/](https://graphql-pokemon.now.sh/), it opens GraphiQL where you can explore the API, use `CTRL + space` to show field suggestions, and `CMD + enter` to expand all nested fields by default. You can also right-click on a field to explore its type etc.

![GraphiQL for pokemon GraphQL API](https://d2mxuefqeaa7sj.cloudfront.net/s_436CC3FB0186E19AFA848D5D9BBDDD002D6719E8B00591E0944C85836193A66D_1533923625458_image.png)

More about GraphQL coming next week in the [Code with Hugo newsletter](https://buttondown.email/hugo) so [subscribe](https://buttondown.email/hugo) if you’re not already.

If you have any questions feel free to tweet at me [@hugo\_\_df](https://twitter.com/hugo__df).

[Andrew Pons](https://unsplash.com/@imandrewpons?utm_medium=referral&utm_campaign=photographer-credit&utm_content=creditBadge "Download free do whatever you want high-resolution photos from Andrew Pons")