Hello! My app is using NestJS on back-end and Vite+React on front-end. Configured serve-static
on NestJS to only use one app (nest) instead of deploying two apps and have to run differents apps. ‘home page’ works, I can visit online website with the url provided from render. But the connection to SocketIO doesn’t work it return WebSocket connection failed
My NestJS has a end-point and also WS-SocketIO from front-end I make a request to api/players/:id
and this end-point works but socket doesn’t.
Here my code from NestJS
// main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
app.setGlobalPrefix('api');
await app.listen(process.env.PORT || 3000);
}
bootstrap();
// app.module.es
@Module({
imports: [
ServeStaticModule.forRoot({
rootPath: join(__dirname, '..', '..', 'client', 'dist'),
exclude: ['/api/(.*)'],
}),
ConfigModule.forRoot(), RedisModule, PlayerModule, GameModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(RequestTraceMiddleware).forRoutes('*');
}
}
// game.gateway.ts
@WebSocketGateway()
export class GameGateway implements OnGatewayConnection, OnGatewayDisconnect {
And my code from React I have the connection to socket on my provider and on vite.config.ts
I have this
// vite.config.ts
export default defineConfig({
base: './',
plugins: [react()],
server: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
ws: true
}
}
}
})
// socket.provider.tsx
useEffect(() => {
const socketConnection = io(import.meta.env.VITE_SOCKET_URL, {
transports: ["websocket"]
});
setSocket(socketConnection);
return () => {
socket?.disconnect();
};
}, []);
On my environment variables I have this
VITE_SOCKET_URL=http://localhost:3000
In localhost if I run the same commands than render execute, the app works and I can connect to my app on localhost:3000
with socketio working. I have read that render set default port to 10000 I tried to configure on environment variable (on render) to those ports but nothing.
Tried:
- Set PORT 10000 on my
@WebSocketGateway
(and also change this on io connection on react) - Add
PORT
variable on render and set to 3000 - Try a different port for my
@WebSocketGateway
, set 4000 and also setVITE_SOCKET_URL=http://localhost:4000
And more combinations but not solution
Does anyone knows what might be the reason it isn’t working? It’s possible to do what I’m trying to approach?
Thanks!!