Upgrade a Request to a ServerWebSocket
Symbol
Server.upgrade
The Request to upgrade
Pass headers or attach data to the ServerWebSocket
true
if the upgrade was successful and false
if it failed
import { serve } from "bun";
serve({
websocket: {
open: (ws) => {
console.log("Client connected");
},
message: (ws, message) => {
console.log("Client sent message", message);
},
close: (ws) => {
console.log("Client disconnected");
},
},
fetch(req, server) {
const url = new URL(req.url);
if (url.pathname === "/chat") {
const upgraded = server.upgrade(req);
if (!upgraded) {
return new Response("Upgrade failed", { status: 400 });
}
}
return new Response("Hello World");
},
});
What you pass to data
is available on the ServerWebSocket.data property
Referenced types
class Request
This Fetch API interface represents a resource request.
- readonly cache: RequestCache
Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching.
- readonly credentials: RequestCredentials
Returns the credentials mode associated with request, which is a string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL.
- readonly destination: RequestDestination
Returns the kind of resource requested by request, e.g., "document" or "script".
- readonly integrity: string
Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI]
- readonly keepalive: boolean
Returns a boolean indicating whether or not request can outlive the global in which it was created.
- readonly mode: RequestMode
Returns the mode associated with request, which is a string indicating whether the request will use CORS, or will be restricted to same-origin URLs.
- readonly redirect: RequestRedirect
Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default.
- readonly referrer: string
Returns the referrer of request. Its value can be a same-origin URL if explicitly set in init, the empty string to indicate no referrer, and "about:client" when defaulting to the global's default. This is used during fetching to determine the value of the
Referer
header of the request being made. - readonly referrerPolicy: ReferrerPolicy
Returns the referrer policy associated with request. This is used during fetching to compute the value of the request's referrer.
- readonly signal: AbortSignal
Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler.