sveltejs / sveltejs/kit

implement "Upgrade" as a function in a api route to support websocket

Open
#12,358 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
20.8k
Forks
2.3k
Avg merge
1d 16h
Merged PRs (30d)
156

Description

Describe the problem

One can easy implement GET, PUT in an api route by a function (see below)

import { json } from '@sveltejs/kit';

export function GET() {
	const number = Math.floor(Math.random() * 6) + 1;

	return json(number);
}
Describe the proposed solution

If we implement UPGRADE Protocol_upgrade_mechanism we could implement websockets aswell

this file is in src/route/chat-app/server.js connect with new WebSocket('/chap-app')

// if this file is in src/route/chat-app/server.js

import { json } from '@sveltejs/kit';

// called when http call wants to upgrade to websocket protocol
export function UPGRADE() {

      // this function will be called after successfull upgrade
       return function connection(ws: WebSocket) {
                         
 	       ws.send('hello');
               ws.onmessage = (event) => {..});
              // other handlers
      }
}

### Alternatives considered

_No response_

### Importance

would make my life easier

### Additional Information

Currently, customers expect some kind of live real time interaction,  a clean solution integrating with sveltekit would be a huge advantage

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the proposed route example in src/route/chat-app/server.js and review the linked HTTP protocol upgrade documentation. Determine how an UPGRADE handler would fit the API route lifecycle and WebSocket connection handling. Done means a documented, supported way to establish and handle WebSocket connections through a SvelteKit route, with tests or examples showing the expected behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
api, backend, web-dev
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.