Subscription not listening to latest Apollo server v3

I’m trying to configure the Subscription in the latest ApolloServer V3 MongoDB and WebSocketServer

so I set up my application in the following way, it’s compiling successfully, normal CRUD operations working, but the subscription service is not triggering and not listening

const { ApolloServer } = require("apollo-server-express");
const { createServer } = require("http");
const express = require("express");
const { ApolloServerPluginDrainHttpServer } = require("apollo-server-core");
const { makeExecutableSchema } = require("@graphql-tools/schema");
const { WebSocketServer } = require("ws");
const { useServer } = require("graphql-ws/lib/use/ws");
const { PubSub } = require("graphql-subscriptions");
const resolvers = require("./graphql/resolvers");
const typeDefs = require("./graphql/typeDefs");
const { MONGODB } = require("./config.js");
const mongoose = require("mongoose");

const pubsub = new PubSub();

(async function () {
  const schema = makeExecutableSchema({ typeDefs, resolvers });

  const app = express();
  const httpServer = createServer(app);

  const wsServer = new WebSocketServer({
    server: httpServer,
    path: "/graphql",
  });

  const serverCleanup = useServer({ schema }, wsServer);

  const server = new ApolloServer({
    schema,
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      {
        async serverWillStart() {
          return {
            async drainServer() {
              await serverCleanup.dispose();
            },
          };
        },
      },
    ],
    cache: "bounded",
    context: ({ req }) => ({ req, pubsub }),
  });

  await server.start();
  server.applyMiddleware({ app });

  mongoose.connect(MONGODB, { useNewUrlParser: true });

  const PORT = 5002;
  httpServer.listen(PORT, () => {
    console.log(
      `Server is now running on http://localhost:${PORT}${server.graphqlPath}`
    );
  });
})();

This is the error message I can see, there is no other error tracing option for me

Unable to connect ‘ws://localhost:5002/graphql’

With F12 error like this , not much info “Websocket connection to
‘ws://localhost:5002/graphql’ failed”

I followed this documentation Subscriptions in Apollo Server - Apollo GraphQL Docs to setup this so far,

may I know how to configure with the latest update,

1 Like

Having the same error if someone have solution it would be nice… I found that it might be in web browser. On inspect browser console I’m getting

The connection to ws://localhost:3000/graphql was interrupted while the page was loading.