Guide: Hyperliquid on SvelteKit (tested starter and findings)

Abierto Apto para principiantes
#62 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
82/100
Tipo de issue
Documentación
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
javascript

Línea de trabajo

Lee las páginas de entorno existentes de Next.js y Vite en docs/hyperliquid/environments/ y, después, añade una página de entorno de SvelteKit con el starter probado y los hallazgos de este issue. Comprueba la página con la configuración de SvelteKit indicada, la ruta REST, el ciclo de vida del WebSocket del navegador y los resultados en desarrollo y producción; la tarea estará terminada cuando la nueva página explique la configuración del adaptador de SvelteKit 3 e incluya el starter probado y las instrucciones para ejecutarlo.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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.

Lenguaje dominante
JavaScript
Estrellas
1
Forks
3
Merge medio
5 h 40 min
PR fusionados (30 d)
57

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Issues similares

Más issues de JavaScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.