Networking
Make HTTP requests, cancel a response, and receive WebSocket messages.
NitroUI installs a native fetch when the runtime starts. Use it directly in app code. For a persistent connection, import WebSocket from nitro-networking.
Fetch a response
Pass a URL string to fetch and check ok before reading the body. The response exposes the HTTP status and final URL. Read a header with response.headers.get(name). Use text() for text, json() for JSON, or arrayBuffer() for binary data. If two consumers need the body, call response.clone() before either reads it.
export async function loadNoteText(url: string): Promise<string> {
const response = await fetch(url)
if (response.ok === false) {
throw new Error(`Could not load note (HTTP ${response.status})`)
}
return response.text()
}Pass the HTTP method, headers and body in the second argument. The method field accepts an uppercase method or a RequestMethod value from nitro-networking. If a redirect crosses origins, the runtime removes any caller-supplied Authorization header. Pass an AbortSignal in the signal field to cancel a request or a pending body read.
const body = JSON.stringify({ text: 'Hello' })
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: body,
})Listen to a WebSocket
Use the WebSocket export from nitro-networking. Add the package as a direct app dependency at the same version as your renderer.
The constructor starts connecting. Register listeners when you create the socket and release them when the screen closes. This hook subscribes to a feed of plain-text messages.
import { useEffect, useState } from 'react'
import { WebSocket } from 'nitro-networking'
export function useLatestMessage(url: string) {
const [message, setMessage] = useState('')
useEffect(() => {
const socket = new WebSocket(url)
const messages = socket.addOnMessageReceivedListener((data) => {
if (typeof data === 'string') setMessage(data)
})
const errors = socket.addOnErrorListener((error) => console.error(error))
return () => {
messages.remove()
errors.remove()
socket.close()
}
}, [url])
return message
}send() accepts a string or an ArrayBuffer. Await each send when message order matters. A resolved send means the transport accepted the message. If the sender needs to know that the other device processed it, include an acknowledgement in your application's protocol.