Skip to content

HTTP requests & WebSockets ​

serverside

Server scripts can call external web services with fetch(url, init?), a version of the browser Fetch API. Use it to post to Discord webhooks, call a bot or analytics endpoint, or pull data from a REST API. For a persistent two-way connection, such as a Discord bot on the gateway, use WebSocket.

ts
const res = await fetch('https://api.example.com/status')
if (res.ok) {
    const status = await res.json()
    echo('service is ' + status.state)
}

It never blocks the game ​

The request runs off the server tick. fetch hands the request to a background worker and returns a promise right away, and the server keeps simulating while the request is in flight. The promise settles on a later tick, and your await resumes there, inside your script as usual. A slow or unreachable service only delays your own code, never the game loop.

You don't have to await at all. A fire-and-forget call such as posting a chat log just needs a .catch (or a try/catch inside an async helper), so a failure is logged rather than reported as an unhandled rejection.

Pending fetches belong to the script that made them. When a script is hot-reloaded, its pending fetches park forever instead of resuming the old code, the same way sleeps and database queries do.

Making requests ​

The second argument, FetchInit, takes:

OptionMeaning
methodGET (default), POST, PUT, PATCH, DELETE, HEAD or OPTIONS
headersA HeadersInit: an object, an array of [name, value] pairs, or a Headers
bodyA string, sent as UTF-8. Use JSON.stringify for JSON. GET/HEAD can't have one
timeoutNon-standard: milliseconds before giving up. Default 15000, max 60000
ts
const res = await fetch('https://api.example.com/scores', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + serverOptions.apiKey },
    body: JSON.stringify({ account: player.account, score: 1200 }),
    timeout: 5000,
})

A body without a Content-Type header is sent as text/plain;charset=UTF-8, so remember to set it for JSON. Requests carry a User-Agent: Mytharyn-GServer/1.0 header unless you set your own.

Passing an object as body is rejected with a TypeError. This is deliberate, because the real Fetch API would silently send "[object Object]".

Reading the response ​

The promise resolves with a Response once the whole body has arrived:

  • status, statusText, and ok (true for 2xx)
  • headers, a case-insensitive Headers: res.headers.get('content-type')
  • url, the final URL, and redirected, true if redirects were followed (up to 5)
  • text(), json() and arrayBuffer() to read the body. You can read the body once: a second call rejects. Check bodyUsed if you're unsure.

Like the browser API, an HTTP error status still resolves. A 404 or 500 is a response, not an exception, so check res.ok. The promise rejects with a TypeError only when there's no response to give: an invalid URL or method, a DNS or connection failure, a timeout, a body over the size limit, or a blocked address. The error's message says which one, and the server log gets a [fetch] line naming your script.

ts
try {
    const res = await fetch(url, { timeout: 3000 })
    if (!res.ok) {
        echo(`lookup failed: HTTP ${res.status}`)
        return
    }
    const data = await res.json()
    // ...
} catch (e) {
    echo('lookup failed: ' + (e instanceof Error ? e.message : String(e)))
}

Limits ​

LimitValue
Schemeshttp and https only
Timeout15 s by default, timeout up to 60 s
Request body / response body4 MB each
RedirectsUp to 5. An https → http downgrade isn't followed; you get the 3xx itself
Concurrency16 requests in flight server-wide. More wait their turn, and past 256 waiting they reject

There is no streaming and no AbortSignal: use timeout to cap how long you wait.

Private networks are blocked ​

By default, fetch and WebSocket refuse to connect to loopback, private, link-local and other reserved addresses: 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10, 169.254.0.0/16 (which includes the cloud metadata endpoint), ::1, fc00::/7, fe80::/10 and similar. The check runs on the address a hostname resolves to, and again on every redirect. A public hostname pointing at an internal IP is refused too. So a script can't probe services running next to the game server.

For local development, for example a script calling a test service on localhost, set fetchAllowPrivate in serveroptions.json and restart the server:

json
{ "fetchAllowPrivate": true }

Don't enable it on a public server.

Example: Discord webhook ​

Discord channels can accept messages through a webhook URL (channel settings → Integrations → Webhooks). The URL contains a secret token, so keep it out of your scripts. Put it in serveroptions.json as a custom key and read it from serverOptions:

json
{ "discordWebhook": "https://discord.com/api/webhooks/123/abc..." }

This script announces joins and leaves in the channel:

ts
// Server script: posts player joins/leaves to a Discord channel through a
// webhook. Keep the webhook URL out of the script — add it to
// serveroptions.json as a custom key:
//
//   "discordWebhook": "https://discord.com/api/webhooks/<id>/<token>"

const WEBHOOK: string = serverOptions.discordWebhook ?? ''

async function postToDiscord(content: string) {
    if (!WEBHOOK) return
    try {
        const res = await fetch(WEBHOOK, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            // allowed_mentions stops player-chosen names from pinging @everyone.
            body: JSON.stringify({ content, allowed_mentions: { parse: [] } }),
        })
        if (!res.ok)
            echo(`[discord] webhook answered ${res.status}: ${await res.text()}`)
    } catch (e) {
        // Network error, timeout or blocked address — never fatal to the game.
        echo('[discord] ' + (e instanceof Error ? e.message : String(e)))
    }
}

function onPlayerJoined(player: Player) {
    // Not awaited: the join handler returns immediately and the post
    // completes on a later tick.
    postToDiscord(`**${player.nick}** joined ${serverOptions.name}`)
}

function onPlayerLeft(player: Player) {
    postToDiscord(`**${player.nick}** left`)
}

A few things worth copying:

  • allowed_mentions: { parse: [] } stops a player named @everyone from pinging your whole Discord server. Do the same anywhere player-controlled text reaches a webhook.
  • The event handlers don't await the post, so login handling never waits on Discord.
  • Discord rate-limits webhooks to roughly 30 messages a minute and answers 429 beyond that. For busy events, batch messages, for example by collecting lines and flushing them from a setInterval every few seconds.

WebSockets ​

WebSocket opens a persistent connection to a ws:// or wss:// server. It works like the browser class of the same name:

ts
const ws = new WebSocket('wss://example.com/live')
ws.onopen = () => ws.send(JSON.stringify({ hello: 'server' }))
ws.onmessage = ev => echo('got ' + ev.data)
ws.onclose = ev => echo(`closed ${ev.code} ${ev.reason}`)

Like fetch, the connection lives off the server tick. Connecting, sending and receiving happen in the background, and your handlers run on a later tick inside the script that created the socket. A chatty or slow server never stalls the game.

Lifecycle ​

A socket moves through readyStateCONNECTING (0) → OPEN (1) → CLOSING (2) → CLOSED (3), and fires:

EventWhen
openThe handshake succeeded. protocol holds the subprotocol the server picked
messageA complete message arrived. data is a string for text frames, an ArrayBuffer for binary ones
errorThe connection failed or broke. Non-standard event.message says why. Always followed by close
closeThe socket is finished, exactly once, always last. A WebSocketCloseEvent with code, reason and wasClean

Use the on… properties or addEventListener(type, fn, { once }). A handler that throws is logged and doesn't stop the other handlers or later events.

  • send(data) queues a string (text frame) or an ArrayBuffer/typed array (binary frame). Calling it while still CONNECTING throws an InvalidStateError, so wait for open. Once the socket is closing, sends are ignored. bufferedAmount tells you how much hasn't gone out yet.
  • close(code?, reason?) closes after the already-queued messages. code is 1000 (default) or 3000–4999, and reason at most 123 bytes. A server that doesn't answer the close within 5 seconds is dropped.
  • The constructor takes optional subprotocols, plus a non-standard WebSocketOptions with handshake headers for services that authenticate the upgrade request.

Close codes you'll see: the server's own code on a clean close, 1005 if it sent none, 1006 when the connection failed or dropped, and 1009 when an incoming message was too large. Event shapes are WebSocketEvent (open/error) and WebSocketMessageEvent.

Sockets belong to their script ​

Unloading or hot-reloading the script that created a socket aborts it silently: no error and no close event, because the old code is gone. The usual pattern is to connect from onCreated, so an update reconnects with the new code.

There's no automatic reconnect. When close fires and you still want the connection, set a setTimeout to reconnect, and back off (1 s, 2 s, 4 s … up to a minute) so a service that's down isn't hammered.

WebSocket limits ​

LimitValue
Schemesws and wss only
Open sockets32 server-wide. Beyond that the constructor throws
Connect timeout15 s, then error + close (1006)
Incoming message16 MB. A bigger one fails the socket (close 1009)
Unsent data16 MB. Beyond that the socket fails
AddressesThe same private-network block as fetch

No compression (permessage-deflate) is negotiated, and binaryType is always 'arraybuffer'.

Example: Discord bot ​

A Discord bot needs the gateway, a WebSocket Discord pushes events through. The bot keeps it alive with heartbeats and answers messages over the REST API with fetch. This one replies to !online with the in-game player list.

Setup:

  1. In the Discord developer portal, create an application, open Bot, reset and copy the token, and enable the Message Content privileged intent.
  2. Invite the bot to your Discord server (OAuth2 → URL generator, scope bot, permissions View Channels and Send Messages).
  3. Add the token to serveroptions.json. It's a secret: keep it out of scripts.
json
{ "discordBotToken": "MTIz..." }
ts
// Server script: a minimal Discord bot on the gateway WebSocket. Anyone in
// the bot's channels can type !online to get the in-game player list.
//
// serveroptions.json needs the bot token (Discord developer portal → your
// app → Bot → Reset Token). Enable the privileged MESSAGE CONTENT intent on
// that page too, or Discord closes the connection with code 4014.
//
//   "discordBotToken": "MTIz..."

const TOKEN: string = serverOptions.discordBotToken ?? ''
const GATEWAY = 'wss://gateway.discord.gg/?v=10&encoding=json'
const API = 'https://discord.com/api/v10'

// GUILDS | GUILD_MESSAGES | MESSAGE_CONTENT
const INTENTS = (1 << 0) | (1 << 9) | (1 << 15)

// Close codes Discord sends for problems a reconnect won't fix (bad token,
// bad/disallowed intents, ...): stop and log instead of looping.
const FATAL = new Set([4004, 4010, 4011, 4012, 4013, 4014])

let socket: WebSocket | null = null
let heartbeat = 0
let seq: number | null = null
let acked = true
let retryDelay = 1000

// Who is online. Rebuilt from joins/leaves, so it starts empty after a hot
// reload until players reconnect.
const online = new Map<string, string>()

function onCreated() {
    if (TOKEN) connect()
    else echo('[discordbot] no discordBotToken in serveroptions.json; bot disabled')
}

function onPlayerJoined(player: Player) {
    online.set(player.account, player.nick)
}

function onPlayerLeft(player: Player) {
    online.delete(player.account)
}

function connect() {
    const ws = new WebSocket(GATEWAY)
    socket = ws
    acked = true

    ws.onmessage = ev => {
        if (typeof ev.data !== 'string') return
        const msg = JSON.parse(ev.data)
        if (msg.s != null) seq = msg.s

        switch (msg.op) {
            case 10: // Hello: start heartbeating, then identify
                startHeartbeat(ws, msg.d.heartbeat_interval)
                ws.send(JSON.stringify({
                    op: 2,
                    d: {
                        token: TOKEN,
                        intents: INTENTS,
                        properties: { os: 'linux', browser: 'mytharyn', device: 'mytharyn' },
                    },
                }))
                break
            case 11: // Heartbeat ACK
                acked = true
                break
            case 1: // The gateway asks for a heartbeat right now
                ws.send(JSON.stringify({ op: 1, d: seq }))
                break
            case 7: // Reconnect
            case 9: // Invalid session
                ws.close(4000, 'reconnecting')
                break
            case 0: // Dispatch
                onDispatch(msg.t, msg.d)
                break
        }
    }

    ws.onerror = ev => echo('[discordbot] ' + ev.message)

    ws.onclose = ev => {
        clearInterval(heartbeat)
        if (ws !== socket) return
        socket = null
        if (FATAL.has(ev.code)) {
            echo(`[discordbot] gateway refused the bot (${ev.code} ${ev.reason}); not reconnecting`)
            return
        }
        echo(`[discordbot] disconnected (${ev.code}); reconnecting in ${retryDelay / 1000}s`)
        setTimeout(connect, retryDelay)
        retryDelay = Math.min(retryDelay * 2, 60_000)
    }
}

function startHeartbeat(ws: WebSocket, interval: number) {
    clearInterval(heartbeat)
    const beat = () => {
        // No ACK since the last beat: the connection is a zombie.
        if (!acked) {
            ws.close(4000, 'heartbeat timeout')
            return
        }
        acked = false
        ws.send(JSON.stringify({ op: 1, d: seq }))
    }
    // Discord asks for a random delay before the first beat.
    setTimeout(() => {
        if (ws.readyState !== WebSocket.OPEN) return
        beat()
        heartbeat = setInterval(beat, interval)
    }, interval * Math.random())
}

function onDispatch(type: string, data: any) {
    if (type === 'READY') {
        retryDelay = 1000
        echo(`[discordbot] logged in as ${data.user.username}`)
    } else if (type === 'MESSAGE_CREATE' && !data.author.bot && data.content.trim() === '!online') {
        const names = [...online.values()]
        reply(data.channel_id, names.length === 0
            ? `Nobody is online on ${serverOptions.name}.`
            : `${names.length} online on ${serverOptions.name}: ${names.join(', ')}`)
    }
}

async function reply(channelId: string, content: string) {
    try {
        const res = await fetch(`${API}/channels/${channelId}/messages`, {
            method: 'POST',
            headers: { Authorization: 'Bot ' + TOKEN, 'Content-Type': 'application/json' },
            // Player nicknames end up in the text; never let them ping anyone.
            body: JSON.stringify({ content, allowed_mentions: { parse: [] } }),
        })
        if (!res.ok) echo(`[discordbot] reply failed: HTTP ${res.status} ${await res.text()}`)
    } catch (e) {
        echo('[discordbot] reply failed: ' + (e instanceof Error ? e.message : String(e)))
    }
}

How it works:

  • Hello → heartbeat → Identify. The gateway's first message (op 10) gives the heartbeat interval. The bot heartbeats on a setInterval and identifies with its token and intents.
  • Zombie detection. If a heartbeat goes unacknowledged (op 11) until the next one, the connection is dead even if it hasn't closed, so the bot closes it and reconnects.
  • Reconnects with backoff on any close, except the codes Discord uses for problems a retry won't fix (bad token 4004, disallowed intents 4014, …). It identifies again rather than resuming. That's simpler, and fine for a small bot (Discord allows 1000 identifies a day).
  • Replies use fetch, with allowed_mentions: { parse: [] } so player names can't ping anyone.
  • Hot-reloading the script aborts the old socket and onCreated connects a fresh one.