3

I am using the following pattern to set up a websockets connection for Apollo/GraphQL subscriptions:

import express from 'express';
import {
  graphqlExpress,
  graphiqlExpress,
} from 'apollo-server-express';
import bodyParser from 'body-parser';
import cors from 'cors';
import { execute, subscribe } from 'graphql';
import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';

import { schema } from './src/schema';

const PORT = 3000;
const server = express();

server.use('*', cors({ origin: `http://localhost:${PORT}` }));

server.use('/graphql', bodyParser.json(), graphqlExpress({
  schema
}));

server.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql',
  subscriptionsEndpoint: `ws://localhost:${PORT}/subscriptions`
}));

// Wrap the Express server
const ws = createServer(server);
ws.listen(PORT, () => {
console.log(`Apollo Server is now running on http://localhost:${PORT}`);
  // Set up the WebSocket for handling GraphQL subscriptions
  new SubscriptionServer({
    execute,
    subscribe,
    schema
  }, {
    server: ws,
    path: '/subscriptions',
  });
});

How can I change the connection to use the secure websockets protocol? Simply changing 'ws://' to 'wss://' does not work.

Langostino
  • 121
  • 2
  • 5

2 Answers2

0

I made a sample for graphql-subscription websocket secure connection.

Here is link: https://github.com/mrdulin/apollo-server-express-starter/tree/master/src/subscription/wss-with-nodejs-server

The key point is you need tls or ssl credentials.

For development, you can generate self-signed credentials using openssl.

Lin Du
  • 88,126
  • 95
  • 281
  • 483
-1

You need to use the https instead of the http package. You also would need to have a certificate. Eather a self-signed or from a certification authority.

It could look like this:

import { createServer } from 'https';

...

// load / get certificate

...

const wss = createServer(sslCredentails, server);
wss.listen(PORT, () => {
console.log(`Apollo Server is now running on https://localhost:${PORT}`);
  // Set up the WebSocket for handling GraphQL subscriptions
  new SubscriptionServer({
    execute,
    subscribe,
    schema
  }, {
    server: wss,
    path: '/subscriptions',
  });
});
Locco0_0
  • 3,420
  • 5
  • 30
  • 42