Connecting with Node.js
Query your GraphQL API using Node.js with plain JavaScript, GraphQL Request, Apollo Client, or Urql as your frontend.
When connecting to API Connect for GraphQL via JavaScript, we recommend that you connect to API Connect for GraphQL using either server-side code or a serverless function as your frontend, to protect your API key from being exposed. The following sections show options for calling GraphQL API with server-side or serverless JavaScript.
Plain JavaScript
You can send queries using Node.js without any special libraries, leveraging the standard Node HTTPS library to form a POST request.
The following example uses a .env
file to store the API key. A
.env
file is useful when you need to store protected keys. Ensure that the file is
added to your .gitignore
file so that it is not inadvertently committed to your
source control repository.
Note: The endpoint URL used in the following example code is for demonstration purposes
only, and does not actually exist. To test this example, configure the path
parameter with the path to an API that you deployed to API Connect for GraphQL.
const https = require('https');
require('dotenv').config();
const data = JSON.stringify({
query: `{
myQuery {
id
name
}
}`,
});
const options = {
hostname: '{ACCOUNT}.stepzen.net',
path: '/api/example/__graphql',
port: 443,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length,
Authorization: 'Apikey ' + process.env.STEPZEN_API_KEY,
'User-Agent': 'Node',
},
};
const req = https.request(options, (res) => {
let data = '';
console.log(`statusCode: ${res.statusCode}`);
res.on('data', (d) => {
data += d;
});
res.on('end', () => {
console.log(JSON.parse(data).data);
});
});
req.on('error', (error) => {
console.error(error);
});
req.write(data);
req.end();
GraphQL Request
GraphQL Request is a library created and maintained by Prisma Labs. It's a lightweight, minimal library that provides only what you need to send and receive GraphQL queries and mutations in the browser or with Node.js.
Complete the following steps to call GraphQL API using GraphQL Request:
-
Invoke
npm install
and importgraphql-request
into your project:import { request, gql, GraphQLClient } from 'graphql-request';
{: codeblock}
-
Instantiate the
GraphQLClient
with the endpoint URL and headers by passing them to the GraphQL API. Then, call therequest()
method on that client to invoke a query:const graphQLClient = new GraphQLClient('https://account-name.stepzen.net/folder-name/api-name/__graphql', { headers: { authorization: 'Apikey ' + process.env.STEPZEN_API_KEY, }, }); const query = gql` { myQuery { id name } } `; const results = await graphQLClient.request(query);
{: codeblock}
Apollo Client
Apollo Client is library created by Apollo that includes functionality for querying, mutations, variables, and so on. Apollo Client also functions as a state management library. You can use Apollo Client to manage local state whether or not you have a GraphQL API to connect. It can also cache the state retrieved from the remote API and combine that with additional local application state.
While not required, Apollo Client integrates easily with React.
Complete the following steps to use Apollo Client:
-
Ensure you have installed Apollo Client using
npm
. -
Import the modules:
gql
,ApolloClient
, andInMemoryCache
; these are required to perform a basic query:import { gql, ApolloClient, InMemoryCache } from '@apollo/client';
InMemoryCache
enables you to configure and control Apollo Client's caching
strategies, which are useful for pulling data on the client. Apollo Client will use the cache
whenever it finds that a query hasn't changed, enabling you to serve responses much faster than
re-retrieving results over the network.
The following example shows how to instantiate an ApolloClient
object and run a
query with it:
const client = new ApolloClient({
uri: 'https://account-name.stepzen.net/folder-name/api-name/__graphql',
cache: new InMemoryCache(),
headers: {
authorization: 'Apikey ' + process.env.STEPZEN_API_KEY,
},
});
const results = await client.query({
query: gql`
{
continents {
name
code
}
}
`,
});
Apollo Client also provides fine-grained control over the HTTP calls you make using Apollo Link, including adding authorization using a Context Link.
See the Apollo Client documentation to learn more about the capabilities of Apollo Client.
Urql
Urql has more features and capabilities than GraphQL Request but fewer than Apollo Client, making it much more lightweight. For example, Urql includes a highly-configurable caching layer similar to Apollo Client, but doesn't include local state management. Urql also has built-in integrations for the React, Svelte, and Vue frameworks, as well as a package for Next.js. See the Urql Comparison table for a feature-by-feature comparison with Apollo Client.
Complete the following steps to use Urql:
-
Import the proper modules:
import { createClient } from 'urql';
-
Create the client and the query, and then pass that to the client's
query()
method:const client = createClient({ url: 'https://account-name.stepzen.net/folder-name/api-name/__graphql', fetchOptions: { headers: { authorization: 'Apikey ' + process.env.STEPZEN_API_KEY }, }, }); const query = ` { continents { name code } } `; const results = await client.query(query).toPromise();
Note: Since the example uses
await
, the stream returned by the query is converted into a JavaScript Promise.
For more information on using Urql, see the Urql documentation.