Guide: Hyperliquid on SvelteKit (tested starter and findings)

Aperta Adatta ai principianti
#62 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
82/100
Tipo di issue
Documentazione
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
javascript
Ambito
documentation

Direzione di ricerca

Leggi le pagine degli ambienti Next.js e Vite esistenti in docs/hyperliquid/environments/, poi aggiungi una pagina dell’ambiente SvelteKit usando lo starter testato e i risultati di questa issue. Verifica la pagina rispetto alla configurazione SvelteKit elencata, alla route REST, al ciclo di vita del WebSocket del browser e ai risultati in sviluppo e in produzione; il lavoro è concluso quando la nuova pagina spiega la configurazione dell’adapter SvelteKit 3 e fornisce lo starter testato e le istruzioni per eseguirlo.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Hyperliquid on SvelteKit: tested starter and findings

There is no SvelteKit page under docs/hyperliquid/environments/ yet (bun, cloudflare-workers, deno, expo, next, node, react, typescript and vite exist). A web search for "hyperliquid sveltekit websocket price feed" this morning returned the Hyperliquid WebSocket docs and our Vite page as the nearest match, so a SvelteKit page would fill an empty spot. The starter below follows the Next.js page (server route) plus the Vite page (browser stream).

Tested 27 Nov 2026 on Node.js 24.22.1 with @siebly/hyperliquid-api 1.0.5, @sveltejs/kit 3.4.1, svelte 5.59.2, vite 8.4.0, @sveltejs/adapter-node 6.0.6 and @sveltejs/vite-plugin-svelte 7.3.2. Browser checks ran in headless Chrome.

Results

Check Dev (vite dev) Production (vite build, node build)
GET /api/price (RestClient in +server.js) 200, BTC mid returned 200, BTC mid returned
Page server render with a top-level import { WebsocketClient } 200 200
Live allMids in the browser (client created in onMount) BTC price shown BTC price shown
Leaving the page (cleanup calls closeAll()) no further errors no further errors

Findings

  1. SvelteKit 3 no longer reads svelte.config.js. With one present, vite build stops with config_file_unsupported. The adapter now goes into the Vite plugin: sveltekit({ adapter: adapter() }) in vite.config.js. Most SvelteKit tutorials still show svelte.config.js, so the page should say this up front.
  2. The SDK import is safe during server rendering. A plain top-level import in +page.svelte renders on the server without errors. Only creating the client and subscribing must wait for onMount, and the function returned from onMount is the place for closeAll().
  3. Server routes work as in Next.js. RestClient in src/routes/api/price/+server.js runs on the Node adapter with no extra config.
  4. WebSocket handshake time. From the test box the browser stream only connected with new WebsocketClient({ connectionTimeout: 5000 }). This is the same connectionTimeout default already raised for the other browser pages, so the starter below keeps the default to match them.

Starter files

package.json

{
  "name": "hyperliquid-sveltekit-quickstart",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite dev --host 127.0.0.1",
    "build": "vite build",
    "start": "node build"
  },
  "dependencies": {
    "@siebly/hyperliquid-api": "latest"
  },
  "devDependencies": {
    "@sveltejs/adapter-node": "6.0.6",
    "@sveltejs/kit": "3.4.1",
    "@sveltejs/vite-plugin-svelte": "7.3.2",
    "svelte": "5.59.2",
    "vite": "8.4.0"
  }
}

vite.config.js

import adapter from '@sveltejs/adapter-node';
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [sveltekit({ adapter: adapter() })],
});

src/app.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    %sveltekit.head%
  </head>
  <body>
    <div style="display: contents">%sveltekit.body%</div>
  </body>
</html>

src/routes/api/price/+server.js

import { json } from '@sveltejs/kit';
import { RestClient } from '@siebly/hyperliquid-api';

export async function GET() {
  try {
    const client = new RestClient();
    const mids = await client.getAllMids();
    const price = mids.BTC;

    if (!price) {
      throw new Error('No price was returned.');
    }

    return json({ symbol: 'BTC', price: String(price) });
  } catch (error) {
    console.error('Price request failed:', error);
    return json(
      { error: 'Exchange price request failed. Check the server logs.' },
      { status: 502 },
    );
  }
}

src/routes/+page.svelte

<script>
  import { onMount } from 'svelte';
  import { WebsocketClient } from '@siebly/hyperliquid-api';

  let restPrice = $state('Loading');
  let livePrice = $state('Connecting');
  let errorText = $state('');

  onMount(() => {
    let stopped = false;
    const ws = new WebsocketClient();

    fetch('/api/price')
      .then((res) => res.json())
      .then((body) => {
        if (!stopped) restPrice = body.price ?? body.error;
      })
      .catch((error) => {
        if (!stopped) errorText = String(error);
      });

    ws.on('message', (message) => {
      if (message.channel !== 'allMids') return;
      const price = message.data?.mids?.BTC;
      if (!stopped && price) livePrice = String(price);
    });
    ws.on('exception', (event) => {
      if (!stopped) errorText = 'WebSocket error, see the console.';
      console.error(event);
    });

    ws.subscribe({ type: 'allMids' })
      .then(() => {
        if (stopped) ws.closeAll();
      })
      .catch((error) => {
        if (!stopped) errorText = String(error);
      });

    return () => {
      stopped = true;
      ws.closeAll();
    };
  });
</script>

<main>
  <h1>BTC price</h1>
  <p>REST (server route): <span id="rest">{restPrice}</span></p>
  <p>Live (WebSocket): <span id="live">{livePrice}</span></p>
  {#if errorText}<p id="error">{errorText}</p>{/if}
</main>

Run with npm install, then npm run dev, or npm run build and npm start (Node adapter, listens on port 3000 by default). Open / for the REST and live prices, or /api/price for the JSON.

Happy to turn this into a PR for starters/hyperliquid/sveltekit plus the environment page if that is easier.

Lingua principale
JavaScript
Stelle
1
Fork
3
Merge medio
5h 40m
PR unite (30g)
57

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Issue simili

Altre issue su JavaScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.