Having trouble with socket.io functionality after deploying my application on Heroku platform

I encountered an issue with my app when deploying it to Heroku after working fine locally with socket.io. The problem lies in the socket setup on the client side, which is configured for localhost:5000. Unfortunately, I am unsure of how to resolve this.

Below is the server file:

const express = require('express');
const app = express();
const path = require('path');

// Creating a server for socket io
const http = require('http');
const socketio = require('socket.io');
const server = http.createServer(app);
module.exports = io = socketio(server);

// Middleware
const morgan = require('morgan');
const bodyParser = require('body-parser');

// Initialize Middleware
app.use(express.json({ extended: false }));

// Router setup
const postRoute = require('./nodeapi/routers/post');
const authRouter = require('./nodeapi/routers/auth');
const usersRouter = require('./nodeapi/routers/users');
const friendRouter = require('./nodeapi/routers/friend');
const chatRouter = require('./nodeapi/routers/chats');
const mongoDB = require('./nodeapi/mongodb-database/db');
const port = process.env.PORT;

// Connect to MongoDB database
mongoDB();

// Middleware usage
app.use(morgan('dev'));
app.use(bodyParser.json());

// Define routes
app.use('/', postRoute);
app.use('/', authRouter);
app.use('/', usersRouter);
app.use('/', friendRouter);
app.use('/', chatRouter);
app.use('/file/', express.static('uploads/'));

// Socket io connection
io.on('connection', (socket) => {
  console.log('Client connected');
  socket.on('disconnect', () => console.log('Client disconnected'));
});
// Serving static assets in production
if (process.env.NODE_ENV === 'production') {
  // Set static folder
  app.use(express.static('./client/build'));
  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
  });
}
// Listening to the port
server.listen(port, () => {
  console.log(`this is port ${port}`);
});

Here is the socket setup on the client side:

import io from 'socket.io-client';

let socket = io('http://localhost:5000');

export default socket;

Answer №1

Instead of allowing your sockets to connect with a fixed URL, consider using

let socket = io(window.location.origin)

This way, your client-side will establish a connection with the server it is deployed on. If your server is deployed elsewhere, you can specify the URL by writing

let socket = io('url_of_deployed_server')

This allows your client-side to effectively communicate with the server through sockets.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn the process of importing two components in Nextjs

I have successfully created two components, a header and a footer. I have been able to call the header component directly in the index.js file and it is working fine. You can see the header section displayed below: enter image description here Now, my iss ...

Error: The media retrieved has an invalid Content-Type header

Currently, I am experimenting with Twilio to send an MMS message. The Twilio server requires me to upload my PNG image so it can store it in their database and provide a unique ID to access that specific PNG. As a newcomer, I am testing out this feature. ...

Building a Node.js application with Mongoose for easy CRUD operations

Can a CRUD scaffold be generated based on the schema model being used? It should not rely on a specific framework, but rather act as a utility. Tools currently in use: ExpressJS MongooseJS MongoDB ...

Tips on how to perform a server-side redirection to a different page in a Nextjs application without refreshing the page while maintaining the URL

I am working on a [slug].js page where I need to fetch data from an API to display the destination page. export async function getServerSideProps({ query, res }) { const slug = query.slug; try { const destination = await RoutingAPI.matchSlu ...

Restricting the input on a React component to only accept alphabet characters from A to Z instead of allowing any keyboard

I am currently facing a challenge with understanding a specific component, particularly the allowForClassification value. This boolean value is passed down to a child component and decides whether a button is displayed or not. The issue arises when tryin ...

What's the best way to modify the style property of a button when it's clicked in

I am working with a react element that I need to hide when a button is clicked. The styles for the element are set in the constructor like this: constructor(props) { super(props); this.state = { display: 'block' }; this. ...

Issue with color attribute not being recognized within Typography component's sx prop

I've run into a problem with the 'sx' property of a Typography component where I can't seem to apply the 'color'. Any insights on what could be causing this issue? https://i.stack.imgur.com/VhWtH.png If I remove the 'co ...

What is the best way to establish a state within a component?

How can I update the state of a component in ReactJS to show notifications again? import React, { useState } from 'react' const NotificationError = (props) => { const [notify, setNotify] = useState(false); console.log("notify.state: ...

The express nodejs web server is moving at a snail's pace, taking anywhere from 4 to 6 seconds to load each

I have been working on a personal cloud server using express and nodejs to serve static files. During development, I added some script files which caused the webserver to suddenly load very slowly upon reloads. Upon inspecting with chrome dev tools, I disc ...

Help! Can't find a crucial file or plugin after setting up Cloud9 ide?

I am currently in the process of setting up Cloud9 on my Debian server for node.js development. I followed a set of simple steps outlined below, but it seems like something is missing and I need guidance on how to resolve this in the most effective way. Wh ...

Rendering server applications using Angular 6 with Express

Currently, I am working with an Angular 6 application and Express server. I am looking to implement a server rendering system using the best practices available, but I have been struggling to find resources that are compatible with Angular 6 or do not util ...

Convert JSON data into an array of strings that are related to each other

I'm encountering an issue with converting JSON into a string array I must convert a JSON into a string array to dynamically INSERT it into our database, as I need this to work for any type of JSON without prior knowledge of its structure. Here is th ...

What is the best way to trigger useEffect when the state being used within the effect is expected to change during the course of the effect's

Exploring the following code snippet: const [list, setList] = useState([]); const [curPage, setCurPage] = useState(0); const fetchItem = useCallback(async ()=>{ const data = await callAPI(); // data is an object setList(prev => [...prev, data]) ...

Node Js issue stemming from unaddressed promises leading to rejection

Hi, everyone! I'm currently facing some challenges while trying to deploy this API. The error message I keep getting is: "UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error may have occurred due to either throwing inside an asyn ...

React Typescript is causing issues with the paths not functioning properly

Looking to simplify my import paths and remove the need for deeply nested paths. Currently working with React and TypeScript, I made adjustments to my tsConfig file like so: { "compilerOptions": { "baseUrl": "src", & ...

Retrieving data from Firestore yields an empty result

Having trouble reading from Firestore within a function, even though writes are working fine. Despite following examples on the given link, the query below and its variations result in an empty promise: module.exports.customerByPhone = phone => { r ...

Issue: bundling process failed. Error message is "SyntaxError in C:/Program Files/reactt/albums/index.android.js: An unexpected token found, expected a semicolon (6:8)"

Below is a code snippet that I currently have: import React from 'react'; import { Text, AppRegistry } from 'react-native'; const App = () => ( <Text>Wow, This is Amazing</Text> ); AppRegistry.registerComponent(&ap ...

Tips on customizing regex to selectively identify specific strings without capturing unrelated ones

Currently, I am working with this regex: /(?<=^|\/)(?:(?!\/)(?!.*\/))(.*?)[:-]v([\d.-]+)(?=\.|$)/ The goal is to extract the captured group from the following strings: rhmtc/openshift-velero-plugin-rhel8:v1.7.9-4 oc-mirror-plug ...

Have you ever wondered how material-ui/Table automatically wraps text in one column? By default, it uses ellipsis to achieve this

The ellipsis is currently being used by default, but I would like it to wrap automatically. Thank you! https://i.stack.imgur.com/bRFtx.png https://i.stack.imgur.com/oaQtp.jpg This is my first time using the material-ui framework and after checking some e ...

Is it possible to configure React JS and React Native together within a single project?

I'm looking to incorporate both React JS for web and React Native for mobile within the same project, utilizing redux and stylesheet. While exploring various repositories like ReactNativeWebHelloWorld, I encountered issues due to outdated versions th ...