# snap_openWebSocket

> Reference documentation for the `snap_openWebSocket` method of the Snaps API.

<SnapsAPIReference method={{"name":"snap_openWebSocket","description":"Open a WebSocket connection to the specified URL with optional protocols.\n\nNote: This method is only available to snaps that have the\n[`endowment:network-access`](https://docs.metamask.io/snaps/features/network-access/)\npermission.","parameters":{"kind":"object","type":"{ url: string; protocols?: string[] | null }","description":"The request parameters for the `snap_openWebSocket` method.","required":true,"properties":[{"kind":"primitive","type":"string","description":"The `wss://` URL of the WebSocket connection to open.","name":"url","required":true},{"kind":"array","type":"string[]","description":"The optional protocols to use for the WebSocket\nconnection.","element":{"kind":"primitive","type":"string","description":null},"name":"protocols","required":false}]},"result":{"kind":"primitive","type":"string","description":"The ID of the opened WebSocket connection, which can be used to reference the\nconnection in subsequent calls to [`snap_sendWebSocketMessage`](https://docs.metamask.io/snaps/reference/snaps-api/snap_sendwebsocketmessage)\nand [`snap_closeWebSocket`](https://docs.metamask.io/snaps/reference/snaps-api/snap_closewebsocket)."},"subjectTypes":["snap"],"examples":[{"examples":[{"name":"Manifest","language":"json","content":"{\n  \"initialPermissions\": {\n    \"endowment:network-access\": {}\n  }\n}\n"},{"name":"Usage","language":"ts","content":"// Open a connection to a WebSocket server, e.g., in the JSON-RPC handler of\n// the Snap:\nsnap.request({\n  method: 'snap_openWebSocket',\n  params: {\n    url: 'wss://example.com/socket',\n    protocols: ['protocol1', 'protocol2'], // Optional\n  },\n})\n\n// Listen for events from the WebSocket connection in the `onWebSocketEvent`\n// handler of the Snap:\nexport const onWebSocketEvent: OnWebSocketEventHandler = async ({ event }) => {\n  switch (event.type) {\n    case 'open':\n      console.log(`WebSocket connection opened with origin ${event.origin}`)\n      break\n    case 'message':\n      console.log(`WebSocket message received from origin ${event.origin}:`, event.data)\n      break\n    case 'close':\n      console.log(`WebSocket connection closed with origin ${event.origin}`)\n      break\n    case 'error':\n      console.error(`WebSocket error from origin ${event.origin}:`, event.error)\n      break\n  }\n}\n"}]}],"restricted":false}}  />
