Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

registering socket IO to vite for sveltekit

I have written a few apps using svelte and sapper and thought I would give sveltekit a go. All in all it works, but I am now running into the issue of registering a worker on ther server.

Basically I am trying to add socket.io to my app because I want to be able to send and receive data from the server. With sapper this wasn't really an issue because you had the server.js file where you could connect socket.io to the polka/express server. But I cannot find any equivalent in sveltekit and vite.

I experimented a bit and I can create a new socket.io server in a route, but that will lead to a bunch of new problems, such as it being on a separate port and causing cors issues.

So I am wondering is this possible with sveltekit and how do you get access to the underlying server?

like image 703
munHunger Avatar asked Oct 15 '22 21:10

munHunger


1 Answers

The @sveltejs/adapter-node also builds express/polka compatible middleware which is exposed as build/middelwares.js which you can import into a custom /server.cjs:

const {
  assetsMiddleware,
  prerenderedMiddleware,
  kitMiddleware,
} = require("./build/middlewares.js");

... 

app.use(assetsMiddleware, prerenderedMiddleware, kitMiddleware);

The node adaptor also has an entryPoint option, which allows bundling the custom server into the build, but I ran into issues using this approach.

Adapters are not used during development (aka npx svelte-kit dev).

But using the svelte.config.js you're able to inject socket.io into the vite server:

  ...
  kit: {
    ...
    vite: {
      plugins: [
        {
          name: "sveltekit-socket-io",
          configureServer(server) {
            const io = new Server(server.httpServer);
            ...
          },
        },
      ],
    },
  },

Note: the dev server needs to be restarted to apply changes in the server code.
You could use entr to automate that.

like image 181
Bob Fanger Avatar answered Oct 18 '22 22:10

Bob Fanger