Graphql-yoga: Socket.io + GraphQL Yoga Server = socketID undefined 404 (Not Found)

Created on 2 Mar 2019  路  6Comments  路  Source: dotansimha/graphql-yoga

Running out of ideas what needs to be done to make GraphQL-Yoga Server to finally work with socket.io:

In browser's console:
image

Client

NextJS CRA Component:

import React, { Component } from 'react';
import io from 'socket.io-client';
socket = io('https://localhost:4444');

export default class OAuthWidget extends Component {
  state = {};
  componentDidMount() {

    console.log( {socket} );
    fetch('https://localhost:4444/').then(res => {
      if (res) {
        console.log('Response from server received');
      }
    });
  }

  render() {
    console.log('socket: ', socket);   // returns undefined

    return <div>Socket id: {socket}</div>;
  }
}

NodeJS, GraphQLServer

(irrelevant cut out for sake of brevity):

index.js:

const fs = require('fs');
const express = require('express');
const session = require('express-session');
const socketio = require('socket.io');
const cookieParser = require('cookie-parser');
const createServer = require('./createServer');

const server = createServer();

server.express.use(express.json());

server.express.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true
  })
);

const io = socketio(server);
server.express.set('io', io);
socketio.listen(server);

server.express.use(cookieParser());

server.start(
  {
    cors: {
      credentials: true,
      origin: ['http://localhost:3000']
    },
    https: {
      key: fs.readFileSync(`./src/ssl/server.key`),
      cert: fs.readFileSync(`./src/ssl/server.crt`)
    }
  },
  async details => {
    console.log(`Server started on: https://localhost:${details.port}`);
  }
);

./createServer.js:

const { GraphQLServer, PubSub } = require('graphql-yoga');
..
function createServer() {
  return new GraphQLServer({
    typeDefs: 'src/schema.graphql',
    resolvers: {
      Query,
      Mutation
    },
    resolverValidationOptions: {
      requireResolversForResolveType: false
    },
    context: req => ({
      ...req,
      db,
      pubsub
    })
  });
}

module.exports = createServer;

what is missing or wrong here?
In official examples we have to create http server and then call .listen() on it passing the express() app :

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(80);

I have declared PORT=4444 constant in process.env variables, I have also tried including it directly into options, no changes

many thanks in advance folks

statustale

Most helpful comment

Hey @schickling, do you have an idea for this problem?
For production environnement we would really like having graphql-yoga and socket.io on the same port.

All 6 comments

i have a same issue. so, i just seperated graphql server and socket.io server.

socketApi.js

import express from 'express';
import http from 'http';
import socketio from 'socket.io';

export const init_socketio_server = () => {
    const app = express();

    const server = http.createServer(app);
    const io = socketio(server);

    server.listen(5000)

    return io;
}

export const socketio_api = (io) => {
    io.on('connection', socket => {

        console.log('sockeet on')
    });
}

server.js

import {init_socketio_server, socketio_api} from "./lib/socketApi";

const server = new GraphQLServer({
    schema,
    context: ({request}) => ({
        request,
        models
    })
})

const io = init_socketio_server();
socketio_api(io);


server.start({
    port: PORT
}, () => {
    console.log(`server running on ${PORT}`)
})

it is working.

Hey @schickling, do you have an idea for this problem?
For production environnement we would really like having graphql-yoga and socket.io on the same port.

Due to inactivity of this issue we have marked it stale. It will be closed if no further activity occurs.

Hey :wave:, It seems like this issue has been inactive for some time. In need for maintaining clear overview of the issues concerning the latest version of graphql-yoga we'll close it.
Feel free to reopen it at any time if you believe we should futher discuss its content. :slightly_smiling_face:

@ScottAgirs @LionelPaulus did you guys ever figure out the solution? Currently I have mine on separate servers but there's a lot convolution coming along with it.

since the server.start return server instance. we can use that to init io, ex:

const server = createServer();
const options = {
    cors: {
      credentials: true,
      origin: ['http://localhost:3000']
    },
    https: {
      key: fs.readFileSync(`./src/ssl/server.key`),
      cert: fs.readFileSync(`./src/ssl/server.crt`)
    },
   port: 4444
}
const init = async () => {
  const serverio = await server.start(options, () => console.log( `Server is running on port http://localhost: 4444 ` ))
  const io = socketio(serverio)
  io.sockets.on('connection', (socket) => {
    console.log('connect', socket.id)
  })
}
init()
Was this page helpful?
0 / 5 - 0 ratings

Related issues

lautiamkok picture lautiamkok  路  4Comments

joshhopkins picture joshhopkins  路  3Comments

CaptainChemist picture CaptainChemist  路  4Comments

2wce picture 2wce  路  4Comments

kv-pawar picture kv-pawar  路  3Comments