Skip to content

Instantly share code, notes, and snippets.

@danba340
Last active January 29, 2023 08:14
Show Gist options
  • Save danba340/1c279cb259500d3713067c06bb71a289 to your computer and use it in GitHub Desktop.
Save danba340/1c279cb259500d3713067c06bb71a289 to your computer and use it in GitHub Desktop.
Socket.io server on Heroku
const app = require('express')();
// Heroku header fixes
app.use(function (req, res, next) {
res.setHeader(
'Access-Control-Allow-Origin',
'http://' + req.headers.host + ':8100',
);
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, OPTIONS, PUT, PATCH, DELETE',
);
res.setHeader(
'Access-Control-Allow-Headers',
'X-Requested-With,content-type',
);
next();
});
// Connect http to express
const http = require('http').Server(app);
// Socket.io init
const io = require('socket.io')(http, {
cors: {
origins: ['http://localhost:8080', 'https://your.app'], // Localhost for testing and your client url
methods: ['GET', 'POST'],
},
// Default:pingInterval: 10000,
// Default:pingTimeout: 5000,
});
// Socket events
io.on('connection', function (socket) {
// Query params
const queryParamValue = socket.handshake.query.queryParamKey;
socket.on('disconnect', function () {
console.log('Disconnect');
});
});
const PORT = process.env.PORT || 3000;
http.listen(PORT, () => {
console.log('listening on port ' + PORT);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment