Skip to content

Native support for web sockets #1491

@AndreasHald

Description

@AndreasHald

We've been attempting to migrate our app from sapper to sveltekit and ran into the problem of web sockets, in sapper we could simply attach the WebSocket server directly to the express server and be done with it, but as per Rich Harris' comments here and here here in sveltekit we don't want to expose direct access to the middlwares thus promoting the node adapter over the serverless ones.

However seeing as some of the serverless providers are starting to support web sockets (cloudflare) (begin) (AWS Lambda) should sveltekit provide a way to handle these connections directly?

A native approach to this could also potentially provide a tool to solve this issue and this

Describe the solution you'd like
An interesting solution could be to expose functions in endpoints in the same way we handle http requests, and then let the adapters handle the rest

routes/api/index.ts

// Handle post requests
export const post: RequestHandler = async (request) => {....}
// Handle web socket requests
export const ws: WebSocketRequestHandler = async (request) => {....}

A concern with this approach could be mixing protocols, within an endpoint could be confusing. Another could be if this becomes too complicated since as far as I know the initial handshake to start a WebSocket connection is handled over http, would this then be handled directly by sveltekit which could be considered too much "magic" since it would have to intercept a get request that would then not make it to the get handler in the endpoint. Or should we let the user implement the get endpoint and return the WebSocket pair and upgrade header.

Describe alternatives you've considered
The way we go about it today is a small script that manipulates the build output of sveltekit as such however this does not work in dev mode which is a pain point.

const instance = createServer({ render: app.render }).listen(PORT, HOST, (err) => {
	if (err) {
		console.log('error', err);
	} else {
		console.log(`Listening on port ${PORT}`);
	}
});
app.server.installSubscriptionHandlers(instance);
export { instance };

Is this a feature that you feel would suit sveltekit? are there any considerations I've overlooked?

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature / enhancementNew feature or requestp1-importantSvelteKit cannot be used by a large number of people, basic functionality is missing, etc.size:largesignificant feature with tricky design questions and multi-day implementation

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions