1

GraphQL playground subscription fails with 400 error code.

WebSocket connection to 'ws://localhost:3000/graphql' failed: Error during WebSocket handshake: Unexpected response code: 400

I have an existing code based on express. I've integrated Apollo v2 this way:

const { ApolloServer, PubSub, gql } = require('apollo-server-express');

    ...

const app = express();

const server = new ApolloServer({
    typeDefs,
     resolvers       
});


server.applyMiddleware({ app });

    ...

app.listen(port, () =>
    console.log(chalk.blue(`App listening on port ${port}!`)),
);

and then i start my existing app on port 3000 and can access the GraphQL playground on http://localhost:3000/graphql. All queries and mutations work as expected

Now I want to add subscriptions. Turns out I need to use an http server:

const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);

and then listen to it on another port:

httpServer.listen(3005, () => {
    console.log(`Server ready at http://localhost:3005${server.graphqlPath}`);
     console.log(`Subscriptions ready at ws://localhost:3005${server.subscriptionsPath}`);
    });  

So I have two servers running. My own on port 3000 and the subscriptions server on 3005. Is that the right way? Is it the only way?

1 Answers1

0

There's no need to call both app.listen and httpServer.listen -- calling httpServer.listen will expose both your Express app and the subscription server.

Additional reading: Express.js - app.listen vs server.listen

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • 1
    `installSubscriptionHandlers` has to be passed an instance of [http.Server](https://nodejs.org/api/http.html#http_class_http_server) which `app` is *not*. Calling `app.listen`, however, will return an instance of `http.Server` that can then be passed to `installSubscriptionHandlers` if you prefer to do that. – Daniel Rearden Sep 04 '19 at 14:54
  • If your "existing code structure" requires you to use `app.listen`, though, you may just need to restructure your code. – Daniel Rearden Sep 04 '19 at 14:56
  • Just looked into the internals of `installSubscriptionHandlers ` and seems like you are right - I need to change the approach. – Sándor Turánszky Sep 04 '19 at 15:21