Websocket server on Vercel
Answered
Jersey Wooly posted this in #help-forum
Jersey WoolyOP
I'm making a game app, so I have something like a socket-server.ts:
However I'm deploying the app to Vercel, and I can't run this in the deployment afaik. What solutions are available?
import { Server, Socket } from 'socket.io';
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?
Answered by joulev
you cannot host ws on vercel at all. either use a third party ws solution like pusher, or host your app in a server
7 Replies
you cannot host ws on vercel at all. either use a third party ws solution like pusher, or host your app in a server
Answer
Jersey WoolyOP
Thank you!
@joulev you cannot host ws on vercel at all. either use a third party ws solution like pusher, or host your app in a server
Jersey WoolyOP
Oh, then is it possible to have somewhere just host the socket-server.ts file? and have my app on vercel access it?
@Jersey Wooly Oh, then is it possible to have somewhere just host the socket-server.ts file? and have my app on vercel access it?
yes you can just buy a server, run your socket server there and connect to it from your app which can be hosted anywhere
Jersey WoolyOP
So something like Render or Railway right? Thanks so much!
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
Jersey WoolyOP
Ahh I see, thank you so much!