#Websocket server on Vercel

9 messages · Page 1 of 1 (latest)

eternal sinew
#

I'm making a game app, so I have something like a socket-server.ts:

import http from 'http';
import { GetSession } from '@/actions/session';

const server = http.createServer((req, res) => {
  res.end('Hello World!');
});

interface CustomSocket extends Socket {
  sessionKey?: string;
}

const sessionData: Record<string, any> = {};

const io = new Server(server, {
  cors: {
    origin: '*',
    methods: ['GET', 'POST'],
    credentials: true,
  },
});

io.on('connection', (socket: CustomSocket) => {
  console.log('a user connected');

  socket.on('setSessionKey', async (sessionKey) => {
    socket.sessionKey = sessionKey;
    if (!sessionData[sessionKey]) {
      sessionData[sessionKey] = {};
    }
    const dbSession = await GetSession(sessionKey);
    console.log(dbSession)
    socket.emit('sessionData', dbSession);
    console.log(`Session key set: ${sessionKey}`);
  });

  socket.on('sendData', (data) => {
    const sessionKey = socket.sessionKey;
    if (sessionKey) {
      sessionData[sessionKey] = data;
      console.log(`Data received for session ${sessionKey}:`, data);
    } else {
      console.log('No session key set for this socket.');
    }
  });

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

server.listen(3001, () => {
  console.log('listening on *:3001');
});

However I'm deploying the app to Vercel, and I can't run this in the deployment afaik. What solutions are available?

weary crestBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

raw vortex
#

you cannot host ws on vercel at all. either use a third party ws solution like pusher, or host your app in a server

eternal sinew
#

Thank you!

weary crestBOT
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer
eternal sinew
raw vortex
eternal sinew
#

So something like Render or Railway right? Thanks so much!

raw vortex
#

yes. idk about render since i never used it but railway absolutely can host ws. you just need to find a place where you can run a server 24/7 compared to vercel where your server only runs when there is an incoming request