> ## Documentation Index
> Fetch the complete documentation index at: https://bun-1dd33a4e-farm-c9035eb1-hot-recreated-import-unwatched.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Build a simple WebSocket server

Start a simple WebSocket server using [`Bun.serve`](/runtime/http/server).

Inside `fetch`, we attempt to upgrade incoming `ws:` or `wss:` requests to WebSocket connections.

```ts server.ts icon="https://mintcdn.com/bun-1dd33a4e-farm-c9035eb1-hot-recreated-import-unwatched/iQiNa3eN_F6jOmGF/icons/typescript.svg?fit=max&auto=format&n=iQiNa3eN_F6jOmGF&q=85&s=b265dc4db2a5a76a3228f58794d844bf" theme={null}
const server = Bun.serve({
  fetch(req, server) {
    const success = server.upgrade(req);
    if (success) {
      // Bun automatically returns a 101 Switching Protocols
      // if the upgrade succeeds
      return undefined;
    }

    // handle HTTP request normally
    return new Response("Hello world!");
  },
  websocket: {
    // TypeScript: specify the type of ws.data like this
    data: {} as { authToken: string },

    // this is called when a message is received
    async message(ws, message) {
      console.log(`Received ${message}`);
      // send back a message
      ws.send(`You said: ${message}`);
    },
  },
});

console.log(`Listening on ${server.hostname}:${server.port}`);
```
