# Deploy SvelteKit

Deploy a SvelteKit app on Pilvia App — server rendering, load functions and form actions in an EU-hosted isolate through a short adapter you keep in your own config, or a fully static build.

SvelteKit runs on Pilvia App both ways. A fully static build deploys with
`@sveltejs/adapter-static`. Server rendering runs in an isolate next to your
data through a short adapter written against SvelteKit's public
[adapter API](https://svelte.dev/docs/kit/writing-adapters). It lives in
your own config: about ten lines plus a small fetch handler.

Tested with SvelteKit 3.4 and Svelte 5.58 on 2026-11-20. SvelteKit 3 keeps
its options in `vite.config.ts`; there is no `svelte.config.js`.

## Server rendering

```ts title="vite.config.ts"
import { rmSync } from "node:fs";
import type { Adapter } from "@sveltejs/kit";
import { sveltekit } from "@sveltejs/kit/vite";
import { defineConfig } from "vite";

// Writes build/client (assets and prerendered pages) and build/server,
// whose fetch.js is the module `pilvia app deploy` deploys.
const pilvia: Adapter = {
  name: "pilvia",
  adapt(builder) {
    rmSync("build", { recursive: true, force: true });
    builder.writeClient("build/client");
    builder.writePrerendered("build/client");
    builder.writeServer("build/server");
    builder.generateServerInstance("build/server/instance.js", { serverDirectory: "build/server" });
    builder.copy("pilvia.fetch.js", "build/server/fetch.js");
  },
};

export default defineConfig({
  // One self-contained server build: no node_modules at runtime.
  ssr: { noExternal: true },
  plugins: [
    sveltekit({
      adapter: pilvia,
    }),
  ],
});
```

```js title="pilvia.fetch.js"
// Copied beside SvelteKit's server output, where ./instance.js is generated.
import { server } from "./instance.js";

export default {
  async fetch(request, env, ctx) {
    await server.init({ env: {} });
    return server.respond(request, {
      platform: { env, ctx },
      getClientAddress: () => request.headers.get("x-real-ip") ?? "",
    });
  },
};
```

```json title="pilvia.app.json"
{
  "name": "my-app",
  "auth": "public",
  "kv": true,
  "bundle": "build/server/fetch.js",
  "assets": "build/client"
}
```

```sh
bun run build
pilvia app deploy
```

Remove `@sveltejs/adapter-auto` from your dependencies.

### Why each line is there

- **`ssr: { noExternal: true }`** bundles every dependency into the server
  build. Without it SvelteKit leaves some of its own modules as bare imports,
  and `pilvia app deploy` resolves them with browser builds. Pages still
  render, but `redirect()` in a form action fails with a 500, so this is easy
  to miss.
- **`server.init({ env: {} })`**: `$env/dynamic/private` and
  `$env/dynamic/public` stay empty, because the platform does not pass
  environment variables to server code at runtime.
- **`getClientAddress`** returns the visitor's address, which the platform
  puts in `x-real-ip`.

## The platform in load functions and actions

The platform's `env` arrives as SvelteKit's `event.platform.env`:
[`env.kv` and `env.cache`](/hosting/kv.md), [`env.user`](/auth/overview.md) and
the [data bindings](/data/overview.md), whatever the manifest grants. Its
`ctx` arrives as `event.platform.ctx`, and
`platform.ctx.waitUntil(promise)` finishes
[work after the response](/reference/runtime.md#work-after-the-response).

```ts title="src/app.d.ts"
declare global {
  namespace App {
    interface Platform {
      env: { kv: { get(key: string, type?: "json" | "text"): Promise<any>; put(key: string, value: unknown): Promise<void> } };
      ctx: { waitUntil(promise: Promise<unknown>): void };
    }
  }
}
export {};
```

```ts title="src/routes/guestbook/+page.server.ts"
import { fail, redirect } from "@sveltejs/kit";
import type { Actions, PageServerLoad } from "./$types";

export const load: PageServerLoad = async ({ platform }) => {
  return { entries: (await platform!.env.kv.get("guestbook", "json")) ?? [] };
};

export const actions: Actions = {
  default: async ({ request, platform }) => {
    const name = String((await request.formData()).get("name") ?? "").trim();
    if (!name) return fail(400, { error: "name required" });
    const kv = platform!.env.kv;
    const entries = (await kv.get("guestbook", "json")) ?? [];
    await kv.put("guestbook", [{ name, at: new Date().toISOString() }, ...entries].slice(0, 20));
    redirect(303, "/guestbook");
  },
};
```

`vite dev` has no platform, so guard `platform` there if you develop
against these routes locally.

## Static: adapter-static

```ts title="vite.config.ts"
import adapter from "@sveltejs/adapter-static";
// …
sveltekit({ adapter: adapter({ fallback: "404.html" }) });
```

```ts title="src/routes/+layout.ts"
export const prerender = true;
```

```json title="pilvia.app.json"
{ "name": "my-site", "auth": "public", "assets": "build" }
```

adapter-static writes `about.html`, which the host serves at `/about`
([how requests resolve](/hosting/static-sites.md#how-requests-resolve)).

## What was tested

| Feature | Result |
|---|---|
| Server rendering, a load function formatting a date with `Intl` in `fi-FI` | ✓ |
| `event.fetch` to the app's own endpoint during a load | ✓ |
| Dynamic route `posts/[slug]`; `error(404)` | ✓ 200 / 404 |
| Unknown path | ✓ SvelteKit's 404 page |
| `+server.ts` endpoint returning JSON | ✓ |
| Form action writing `env.kv`, plain POST and `use:enhance` | ✓ 303, then the new row |
| `fail(400)` on empty input | ✓ |
| POST without an `Origin` | ✓ refused by SvelteKit, 403 |
| Hydration, client state and client-side navigation in a browser | ✓ no console errors |
| A prerendered page | ✓ served by the host, no isolate |
| `getRequestEvent()` after an `await` | ✓ the isolate has `AsyncLocalStorage` |
| Hashed client files under `_app/immutable/` | ✓ `max-age=31536000, immutable` |
| adapter-static, `/about` from `about.html`, client navigation | ✓ |

The recipe and adapter-static were re-tested on 2026-11-20 against the
runtime and engine that went live that day.
