Nathan Lu
Nathan Lu

Reputation: 69

How to deploy Socket.io and SvelteKit web app to Vercel?

I am working on a .io-style multiplayer game that uses Socket.io and SvelteKit. When hosting the project locally with a development server, everything works fine, but when I deploy to Vercel, it logs Failed to load resource: the server responded with a status of 404 ().

Here is my current express server.ts (non-functional)

import http from "HTTP";
import { handler } from './build/handler.js';
// Gives error: An import path cannot end with a '.ts' extension.
import injectSocketIO from "src/lib/socket-handler.ts";
import express from 'express';

const app = express();
const server = http.createServer(app);

injectSocketIO(server)

app.use(handler);

// Should I change something here?
server.listen(3000, () => {
    console.log('Running on http://localhost:3000');
});

I am able to run a development server locally using the vite plugin like so:

import injectSocketIO from "./src/lib/socket-handler";

plugins: [sveltekit(), {
    name: "sveltekit-socket-io",
    configureServer(server) {
        injectSocketIO(server.httpServer);
    },
}],

I tried following the steps outlined here, but I am using socket-handler.ts instead of socket-handler.js and am unfamiliar with how to set a startup script to run with Vercel. Any help would be greatly appreciated!

Upvotes: 1

Views: 1460

Answers (1)

Christian Vano
Christian Vano

Reputation: 111

I'm still looking for a better way, but I fixed the same problem by taking the Express server outside of the Svelte src directory.

My code is the same as yours, only importing socket-handler.js from the root directory:

// server.js
import express from 'express'
import injectSocketIO from './socket-handler.js'
import { handler } from './build/handler.js'

const app = express()
const server = http.createServer(app)

// Inject SocketIO
injectSocketIO(server)

// SvelteKit handlers
app.use(handler)

server.listen(3000, () => {
  console.log('Running on http://localhost:3000')
})

Now run npm run build && node server.js to build the Svelte app and then start the Express server.

This tutorial put me on to that solution. You basically run a standard Express server, add socket.io and let SvelteKit handle the rest using Express middleware.

Upvotes: 1

Related Questions