vite-plugin-node icon indicating copy to clipboard operation
vite-plugin-node copied to clipboard

Not working for Nestjs with socket

Open Jedliu opened this issue 1 year ago • 3 comments

Hi, thanks for this great plugin. This works well until I add the socket with Nestjs. I have a working demo here nestjs-vite-demo.

Socket is working with Nest default cli.

1- Start the server

pnpm run start

2- Visit the page localhost:3000. You will see the client page. image The status shows the client is connected to the socket server, and you can click Send Message to send the message to the server and get the reply from the server.

Here are the steps to reproduce the problem.

1- Start the server with vite

pnpm run start:vite

2- Visit the page localhost:3000. The client will never connect to the server. image

Possible solution.

#87 I can't get the production build working with Vite. I will report on the other issue as well.

I hope someone can give a hint on how to solve this. Thank you!

Jedliu avatar Jun 02 '24 09:06 Jedliu

By the way, the socket test runs well with vitest.

pnpm run test:vitest

Jedliu avatar Jun 02 '24 09:06 Jedliu

the same issue with socket.io If we run npm run dev then socket doesn't work.

If we run npm run build and then run node main.js all works fine

import express from "express";
import cors from "cors";
import { createServer } from "http";
import { Server } from "socket.io";
import { type Request, type Response } from "express";

const app = express();
const httpServer = createServer(app);


app.use(
  cors({
    origin: "*",
  })
);

app.get("/", (req, res) => {
  res.send("Socket server is running!");
});

const io = new Server(httpServer, {
  cors: {
    origin: (origin, cb) => {
      cb(null, true);
    },
  },
});


io.on("connection", (socket) => {
  console.log("Connection established!");

  socket.on("message", (message) => {
    console.log("Received", message);
    socket.send("message", message);
  });
});

httpServer.listen(3000);

export const viteNodeApp = app;

olegdunkan avatar Jan 18 '25 08:01 olegdunkan

Vite will start a WebSocket server for HMR in the development environment. I wonder if I can do something with this?

Connecting it at development runtime is easy:

const socket = new WebSocket("http://localhost:5173", "vite-hmr")

Groupguanfang avatar Feb 17 '25 14:02 Groupguanfang