← Integrations

Web framework · TypeScript, Svelte

Numerology in SvelteKit: a form action, $env/static/private and three calls

A SvelteKit form action is server code that a plain HTML form can post to, which makes it a natural home for an AstroNode call. The key comes from $env/static/private, and SvelteKit refuses to build if browser code reaches for it.

Updated

How this page was checked: $lib/server/astronode.ts and the form action in +page.server.ts were executed on Node 24 against the in-memory API, by calling actions.default with a real form-encoded Request. $env/* and fail from @sveltejs/kit were replaced by one-line stand-ins because SvelteKit is not installed on the build machine. The .svelte page was not rendered.

Private, static, dynamic

bash
# .env at the project root (gitignored)
ASTRONODE_API_KEY=aie_live_...
# optional; read at runtime through $env/dynamic/private
ASTRONODE_BASE_URL=https://api.astronode.dev
ModuleContainsWhen it is read
$env/static/privateVariables without the PUBLIC_ prefix, server code onlyInlined at build time
$env/dynamic/privateThe same set, server code onlyAt runtime, from the process
$env/static/publicOnly PUBLIC_-prefixed variablesInlined at build time, browser too

The key comes from the static module, so a missing key fails the build rather than the first request. The base URL comes from the dynamic module, so one build can point at staging or production. Put the module under src/lib/server/: SvelteKit will not let anything that runs in the browser import from that folder.

The client module

src/lib/server/astronode.ts:

ts
import { env } from "$env/dynamic/private";
import { ASTRONODE_API_KEY } from "$env/static/private";

const BASE = env.ASTRONODE_BASE_URL ?? "https://api.astronode.dev";
const NUMBERS = ["life-path", "expression", "soul-urge"] as const;

export type CoreNumber = { value: number; is_master: boolean; chain: number[] };
export type CoreNumbers = Record<(typeof NUMBERS)[number], CoreNumber>;

export class AstroNodeError extends Error {
  constructor(public status: number, public code: string, message: string) {
    super(message);
  }
}

// One number per request: three calls, run in parallel.
export async function coreNumbers(name: string, dob: string): Promise<CoreNumbers> {
  const pairs = await Promise.all(
    NUMBERS.map(async (number) => {
      const res = await fetch(`${BASE}/v1/numerology/pythagorean`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${ASTRONODE_API_KEY}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ name, dob, number }),
      });
      const json = await res.json();
      if (!res.ok) {
        const detail = json.error.details?.[0]?.message ?? json.error.message;
        throw new AstroNodeError(res.status, json.error.code, detail);
      }
      const { value, is_master, reduction_chain } = json.data.result;
      return [number, { value, is_master, chain: reduction_chain }] as const;
    }),
  );
  return Object.fromEntries(pairs) as CoreNumbers;
}

/v1/numerology/pythagorean returns one number per request (number is required, and there are 32 of them), so a page that shows three numbers makes three billable calls. Promise.all runs them in parallel; if any one fails, the whole submission fails, which is what you want for a single form.

The form action

src/routes/numerology/+page.server.ts:

ts
import { fail } from "@sveltejs/kit";
import { AstroNodeError, coreNumbers } from "$lib/server/astronode";
import type { Actions } from "./$types";

export const actions = {
  default: async ({ request }) => {
    const form = await request.formData();
    const name = String(form.get("name") ?? "").trim();
    const dob = String(form.get("dob") ?? "");
    if (!name) return fail(400, { name, dob, message: "Enter the full birth name." });

    try {
      return { name, numbers: await coreNumbers(name, dob) };
    } catch (err) {
      if (err instanceof AstroNodeError && err.status === 400) {
        return fail(400, { name, dob, message: err.message });
      }
      throw err; // 401/429/5xx: let SvelteKit's error page handle it
    }
  },
} satisfies Actions;
What the action returned for name "Asha Rao", born 15 August 1990
Numbervaluereduction_chain
life-path6[15, 6]
expression9[27, 9]
soul-urge9[9]

Returning fail(400, …) keeps the user's input in form so the page can show it again with a message. Posting dob=15/08/1990 produced { status: 400, data: { message: "expected YYYY-MM-DD" } }: the action passes AstroNode's own field message through. A browser <input type="date"> always submits YYYY-MM-DD, so this happens only when the field is free text. For which letters count as vowels and how the reductions work, see Chaldean vs Pythagorean numerology.

The page

src/routes/numerology/+page.svelte (Svelte 5):

svelte
<script lang="ts">
  import { enhance } from "$app/forms";
  let { form } = $props();
</script>

<form method="POST" use:enhance>
  <input name="name" value={form?.name ?? ""} required />
  <input name="dob" type="date" value={form?.dob ?? ""} required />
  <button>Calculate</button>
</form>

{#if form?.message}
  <p role="alert">{form.message}</p>
{/if}
{#if form?.numbers}
  <dl>
    {#each Object.entries(form.numbers) as [label, n]}
      <dt>{label}</dt>
      <dd>{n.value}{n.is_master ? " (master)" : ""} - {n.chain.join(" → ")}</dd>
    {/each}
  </dl>
{/if}

Without JavaScript the form posts and the page re-renders with form filled in. With use:enhance it does the same without a full reload. Either way, only the three numbers reach the browser.

The import that fails the build

  • Importing `$env/static/private` from code that runs in the browser (a +page.svelte, a universal +page.ts load, or any $lib file they import) is a build error, not a warning. The fix is to move the call into +page.server.ts, a +server.ts endpoint or $lib/server/. Do not switch to $env/static/public.
  • Building without the variable. A static import of a name that is not set at build time also fails the build. That is common in CI, where the key exists only at runtime. Either give the build step the variable, or read the key with env.ASTRONODE_API_KEY from $env/dynamic/private.
  • Renaming it `PUBLIC_ASTRONODE_API_KEY` makes every error go away and inlines the key into the client JavaScript. Revoke any key that has been built that way.

Questions

Which AstroNode endpoints does the SvelteKit example call?
1 endpoint: Pythagorean Numerology (POST /v1/numerology/pythagorean).
Was the SvelteKit code on this page actually run?
$lib/server/astronode.ts and the form action in +page.server.ts were executed on Node 24 against the in-memory API, by calling actions.default with a real form-encoded Request. $env/* and fail from @sveltejs/kit were replaced by one-line stand-ins because SvelteKit is not installed on the build machine. The .svelte page was not rendered.