Implementing GraphQL subscriptions
After explaining GraphQL subscriptions, let's look at how we can use Apollo Server to implement them in our application. Because subscriptions utilize WebSocket rather than HTTP, we must use a second GraphQL endpoint created for subscriptions that uses the WebSocket protocol rather than HTTP:
- Begin by installing the packages listed as follows:
npm install subscriptions-transport-ws graphql-subscriptions
- Add the following imports to the
server/src/index.ts
file:import { createServer } from 'http'; import { execute, subscribe } from 'graphql'; import { SubscriptionServer } from 'subscriptions- transport-ws';
- Following that, we must launch two servers, HTTP and WebSocket. As a result, we must create
http.Server
by providing our Express app to thecreateServer()
function in the body of thestartApolloServer()
function, as seen here:async function startApolloServer() { const PORT...