Skip to main content

🎥 How to Set Up GraphQL Subscriptions for Blockchain Data

Updated on
Aug 4, 2023

3 min read

In this video, we briefly explain how GraphQL subscriptions work and guide you through setting them up using QuickNode's Graph API. Go to our docs to learn more about our Live Graph.

Subscribe to our YouTube channel for more videos!

Here is the code sample shown in the video:

const WebSocket = require('ws');
const { createClient, stringifyMessage, parseMessage } = require('graphql-ws');

// WebSocket endpoint URL
const websocketUrl = 'wss://api.quicknode.com/graphql/quickalerts/subscriptions';

const subscriptionQuery = `
subscription OnNewMint($input: SubscriptionOnNewMintInput!) {
onNewMint(input: $input) {
blockHash
blockNumber
collection {
address
name
circulatingSupply
totalSupply
symbol
slug
}
recipient {
address
ensName
walletNFTs {
totalCount
}
walletCollections {
totalCount
}
}
}
}
`;

const client = createClient({
url: websocketUrl,
webSocketImpl: WebSocket,
connectionParams: {
'x-api-key': 'GRAPH_API_KEY'
},
stringifyMessage,
parseMessage,
});

// use
(async () => {
try {
client.subscribe(
{
query: subscriptionQuery,
variables: {
input: {
network: "POLYGON_MAINNET"
}
}
},
{
next: (result) => {
// Handle the received subscription data
console.log('Received data:', JSON.stringify(result));
},
error: (error) => {
// Handle subscription errors
console.error('Subscription error:', error);
},
complete: () => {
console.log('Subscription complete')
},
}
);
} catch (err) {
console.log(err)
}
})();

We ❤️ Feedback!

Let us know if you have any feedback or requests for new topics. We'd love to hear from you.

Share this guide