Using socket.io with React app and node backend - socket not connecting

Viewed 36

I am trying to get just a basic grasp of how I can integrate socket.io with a React app, and haven't really made much progress after looking at a bunch of examples and youtube videos.

Here is my server.js:

const express = require('express');
const cors = require('cors');
const path = require('path');
const dotenv = require('dotenv');
const socket = require('socket.io');

dotenv.config({ path: './config.env' });
const app = express();
app.use(express.json());
app.use(cors());
const port = process.env.PORT || 8000;


const http = require('http').Server(app);

const server = http.listen(port, () => {
    console.log(`App running on port ${port}`);
});


//const io = socket(server, ...) doesn't work here either
const io = socket(http, {
    cors: {
        origin: '*',
    },
});

io.on('connection', (socket) => {
    console.log(`user connected from ${socket.handshake.address}`);
    socket.on('join', (data) => {
        console.log(data.message);
    });
});

Here is my App.jsx file - as you can see, I just have a placeholder for the content of the page, and I just want to see the socket connect to the server.

import './App.css';
import { io } from 'socket.io-client';
import React, { useEffect, useRef } from 'react';

function App() {
    const socket = useRef();

    useEffect(() => {
        socket.current = io('https://localhost:8000');
        socket.current.emit('join', { message: 'hi!' });
        console.log('hi');
    }, []);

    return <div className="App">This is just a placeholder</div>;
}

export default App;

When I navigate to localhost:3000 (where the react app is hosted), I see the "this is just a placeholder" message, and the console logs "hi" (twice...why?), but on the server side, I do not see any indication that the socket has connected.

Can anyone tell me what I am doing wrong here?

Thanks in advance!

0 Answers
Related