Bonus: SvelteKit Basics: Project Structure, Working with AI Skills and Automatic Deployment
番外:SvelteKit 入門:專案結構、搭配 AI skill 與自動部署
A beginner’s tour of SvelteKit using the shop’s back office: how Svelte and SvelteKit divide the work, files as routes, where load runs, SSR, CSR, prerendering and adapters, environment variables and secrets, and testing. Then a skill that keeps an AI agent on the project’s conventions, and automatic deployment to Cloudflare Pages with GitHub Actions, including PR previews and rollback.
In this article
- What this article solves
- Step 1: What SvelteKit is, and when to use it
- Step 2: Create the project and understand its structure
- Step 3: The basics of Svelte 5 components
- Step 4: Loading data, and where code runs
- Step 5: Rendering modes and adapters
- Step 6: Environment variables and secrets
- Step 7: Testing and checks
- Step 8: Working with AI skills
- Step 9: Deploying automatically to Cloudflare Pages with GitHub Actions
- Step 10: Rolling back, and comparing ways to deploy
- Common pitfalls
- Key takeaways
- References
- Next
The previous article, “Writing a Claude Code Skill That Cites Its Sources”, made the AI back every sentence about the team's documents with a source you can check. Up to this point the whole series has been about the back end: Go services, databases, messaging and deployment. This bonus article moves to the front end. The shop's back office and storefront both need screens that people can see, and in the end those screens all talk to api-gateway. Here we build a back office for the shop with SvelteKit, starting from the concepts: what a project looks like, where the code runs, how to get an AI agent to follow the project's conventions, and how to check, build and deploy automatically once code is pushed to GitHub.
What this article solves
The shop's back end is stable: api-gateway exposes APIs such as /v1/orders, with order, payment and inventory behind it. Yet customer support and operations still look up orders with a database query tool, because there is no back office. The team decides to build a small but complete one, shop-admin: list orders, filter by status, and cancel orders that have not been paid. Before starting, they are stuck on a few questions:
- There are so many front-end frameworks. Is SvelteKit a good fit? Which situations suit it, and which do not?
- Where exactly does the code run? The back office must send a token when it calls
api-gateway, and that token must never reach the browser. Which files run on the server and which in the browser? - The Svelte that AI writes is often the old syntax. Models have seen a great many tutorials for older versions, and the code they produce fails to compile in a new project. How do we make them follow the project's conventions?
- Deploying by uploading files by hand goes wrong easily. Someone builds on their own machine, forgets to run the tests, ships the wrong version; all of it has happened. How do we get to "push, and it is checked and deployed automatically, and if something breaks we can roll back in one click"?
This article works through it step by step:
- Get to know SvelteKit: how it divides the work with Svelte, and when it does and does not fit.
- Create a project and understand the folder structure and "files are routes".
- The basics of Svelte 5 components:
$state,$derived,$effect,$propsand events. - Loading data: where
loadruns, why secrets can live only on the server, and form actions. - Rendering modes (SSR, CSR, prerendering, hydration) and adapters.
- Environment variables and secrets.
- Testing and checks.
- Working with AI skills: keeping an agent on SvelteKit 3 and the project's conventions.
- Deploying automatically to Cloudflare Pages with GitHub Actions, including PR previews.
- Rolling back, and a comparison of three ways to deploy.
This article is based on SvelteKit 3 and Svelte 5 (a project created with sv 1.7). SvelteKit 3 changed a fair amount, including the config file, the import alias and environment variables, and many tutorials online still show the old version. Step 8 deals with that specifically.
Step 1: What SvelteKit is, and when to use it
First, separate the two names:
- Svelte is a compiler for components. You write
.sveltefiles (HTML, styles and a<script>block), and at build time Svelte compiles them into JavaScript that updates the page directly. It is only concerned with "how one component draws itself and how it updates when data changes". - SvelteKit is an application framework built on Svelte. It handles everything else a website needs: routing (which URL maps to which page), data loading, server-side rendering and prerendering, form submissions, API endpoints, and finally how to deploy to different platforms (adapters). Underneath, Vite provides the dev server and the bundling.
Figure: your files sit at the top; SvelteKit handles routing, data loading, rendering modes and adapters; Svelte compiles each component to JavaScript; Vite runs the dev server and bundles.
To compare with the shop: Svelte is like the individual screen components you write (an order list, a button), and SvelteKit plays the role that api-gateway plays for the back-end services, deciding who handles a request when it arrives, where the data comes from and how the response goes out.
When SvelteKit fits:
| Situation | Why it fits |
|---|---|
Internal back offices and dashboards (shop-admin) | Server-side load can call internal APIs with a token safely; form actions make writes simple |
| Content sites, documentation, blogs | The whole site or some pages can be prerendered to static HTML: fast, and search-friendly |
| Apps that need server rendering (storefront, account pages) | The first load is complete HTML, later navigation happens in the browser: both benefits |
| Small teams that want less boilerplate | The component syntax is compact, and the compiled JavaScript is usually small too |
When you do not necessarily need it:
- A single page with almost no interactivity (a campaign page, one document): plain HTML, or a content-focused static site generator such as Astro, is simpler. You would not use the framework's routing and data loading.
- A team deeply invested in the React ecosystem: the component libraries, design system and familiar tools are all there, and the cost of learning and migrating often outweighs SvelteKit's own advantages. That is not a flaw in SvelteKit, just a trade-off.
- You only need an API, with no screens: write the service in a back-end language (Go, as in this series); there is no need for a front-end framework.
Step 2: Create the project and understand its structure
Create the project with the official command-line tool, sv. In interactive mode you only type npx sv create shop-admin, and it asks you in turn which template, whether to use TypeScript and which add-ons. To specify everything at once without prompts, spell out all the options:
npx sv create shop-admin --template minimal --types ts \
--add vitest="usages:unit" sveltekit-adapter="adapter:cloudflare+cfTarget:pages" \
--install npm
cd shop-admin
npm run gen # generate the Cloudflare types file worker-configuration.d.ts
npm run dev # http://localhost:5173This command picks the minimal template, TypeScript, Vitest unit tests, and the adapter for deploying to Cloudflare Pages. When it finishes, sv reminds you to run npm run gen to update the Cloudflare types.
Figure: schematic. ① Run the create command; ② after installing, sv lists the next steps; ③ the files created, with what each is for on the right.
The files created and what they are for:
| File / folder | Purpose |
|---|---|
src/routes/ | Routes. The folder structure is the URL structure |
src/lib/ | Shared components and code, imported as #lib/... |
src/app.html | The HTML shell shared by every page |
src/app.d.ts | App-wide types (for example the error object, locals) |
static/ | Files copied unchanged to the site root (robots.txt, icons) |
vite.config.ts | Vite and SvelteKit configuration; the adapter is set here too |
package.json | Scripts (dev, build, check, test) and the #lib alias in its imports field |
wrangler.jsonc | Cloudflare configuration: project name, compatibility date, where the build output goes |
tsconfig.json | Extends the $app/tsconfig that SvelteKit generates |
If you have read older tutorials, you will notice there is no svelte.config.js. SvelteKit 3 no longer supports that file; the configuration is passed to the sveltekit() plugin in vite.config.ts instead. The $lib alias has also been replaced by #lib in package.json, and imports must include the file extension (#lib/money.ts).
Files are routes
Under src/routes/, each folder is a segment of the URL, and the files starting with + in that folder decide what the URL does:
Figure: files on the left, the matching URLs on the right. +layout.svelte wraps every page below it; the square brackets in [id] mark a URL parameter; +server.ts is an API endpoint that returns data rather than a page.
| File | What it does | Where it runs |
|---|---|---|
+page.svelte | The screen for this URL | Server (first time) and browser |
+page.ts | Universal load: prepares the data the screen needs | Server (first time) and browser (on navigation) |
+page.server.ts | Server load and form actions | Server only |
+layout.svelte | A frame around every page at this level and below (nav, footer) | Server and browser |
+layout.ts / +layout.server.ts | Data the frame needs; also page options shared by a whole section | As the two rows above |
+server.ts | An API endpoint exporting GET, POST and so on, returning a Response | Server only |
+error.svelte | The screen shown when something at this level fails | Server and browser |
The back office's route plan:
src/routes/
├── +layout.svelte frame shared by every page
├── +page.svelte / home page
├── +page.ts home page options (prerender)
├── orders/
│ ├── +page.server.ts /orders fetch orders from api-gateway with a token; cancel action
│ └── +page.svelte order list
├── status/
│ ├── +page.ts /status universal load
│ └── +page.svelte
└── api/health/
└── +server.ts /api/health returns JSONStep 3: The basics of Svelte 5 components
Svelte 5 declares reactive state with runes: keywords that start with $ and look like functions. The four most common:
| Rune | What it does | Analogy |
|---|---|---|
$state() | Declares state that changes and should update the screen | A spreadsheet cell you type into |
$derived() | A value computed from other state, recomputed when its sources change | A formula cell in a spreadsheet |
$effect() | A "side effect" to run after state changes (touching things other than the DOM) | Sending a notification when a formula cell changes |
$props() | Receives the values passed in by the parent component | A function's parameters |
A minimal component:
<script lang="ts">
let { step = 1 }: { step?: number } = $props();
let count = $state(0);
let doubled = $derived(count * 2);
$effect(() => {
document.title = `Clicked ${count} times`;
});
</script>
<button onclick={() => (count += step)}>Clicked {count} times</button><p>Doubled: {doubled}</p>A few points:
- Events are ordinary attributes:
onclick={...}, not the oldon:click. - Prefer
$derivedto$effect. If a value can be computed with$derived, do not use$effectto "sync" another piece of state; keep$effectfor things that really touch the outside world, such as changingdocument.titleor driving a third-party chart.$effectruns only in the browser, never during server rendering. - Old syntax is an error in a new project. A project created by
svforces runes mode for the project's own files invite.config.ts, so writingexport let step = 1givesCannot use 'export let' in runes mode — use '$props()' instead. That is a good thing: the mistake is stopped at compile time rather than discovered at run time.
Step 4: Loading data, and where code runs
This is SvelteKit's most important concept and the easiest one to get confused about. In the same project, some code runs only on the server, some only in the browser, and some in both.
Figure: the left side runs only on the server and may read secrets and reach the internal network; the right side is shipped to the browser, where anyone can open the developer tools and read it. Only serialised data crosses the middle.
The rule for telling them apart is simple:
- Modules with
.serverin the file name (+page.server.ts,hooks.server.ts) or undersrc/lib/server/run only on the server. SvelteKit prevents browser code from importing them. - The universal
loadin+page.tsand+layout.tsruns on the server on the first page load, and in the browser when navigating within the site afterwards. So it is also bundled into the browser's JavaScript. .sveltecomponents run once on the server to produce HTML during server rendering, then again in the browser to take over interaction.
So the code that calls api-gateway belongs on the server side. First, a small server-only module:
// src/lib/server/gateway.ts
import { ADMIN_API_TOKEN, API_GATEWAY_URL } from '$app/env/private';
export type Order = {
id: string;
status: 'pending' | 'paid' | 'cancelled';
amount: number; // minor units
currency: string;
};
// fetch is passed in from load or an action; SvelteKit handles cookies and relative URLs
export async function gateway(
fetch: typeof globalThis.fetch,
path: string,
init: RequestInit = {}
) {
const res = await fetch(`${API_GATEWAY_URL}${path}`, {
...init,
headers: { ...init.headers, authorization: `Bearer ${ADMIN_API_TOKEN}` }
});
if (!res.ok) throw new Error(`api-gateway ${path}: ${res.status}`);
return res;
}The orders page's server load and the form action that cancels an order:
// src/routes/orders/+page.server.ts
import { error, fail } from '@sveltejs/kit';
import { gateway, type Order } from '#lib/server/gateway.ts';
import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ fetch, url }) => {
const status = url.searchParams.get('status') ?? 'all';
try {
const res = await gateway(fetch, `/v1/orders?status=${encodeURIComponent(status)}`);
const orders: Order[] = await res.json();
return { orders, status };
} catch {
error(502, 'Orders are temporarily unavailable');
}
};
export const actions: Actions = {
cancel: async ({ request, fetch }) => {
const id = (await request.formData()).get('id');
if (typeof id !== 'string' || id === '') return fail(400, { message: 'Missing order ID' });
await gateway(fetch, `/v1/orders/${encodeURIComponent(id)}/cancel`, { method: 'POST' });
return { cancelled: id };
}
};The page component receives the data returned by load, and the form returned by an action, through $props():
<script lang="ts">
import { enhance } from '$app/forms';
import { formatAmount } from '#lib/money.ts';
import type { PageProps } from './$types';
let { data, form }: PageProps = $props();
let keyword = $state('');
let shown = $derived(data.orders.filter((o) => o.id.includes(keyword.trim())));
</script>
<h1>Orders</h1>
<label>Search by order ID <input bind:value={keyword} /></label>
<button onclick={() => (keyword = '')}>Clear</button>
<p>{shown.length} orders</p>
{#if form?.message}<p role="alert">{form.message}</p>{/if}
<ul>
{#each shown as order (order.id)}
<li>
{order.id}: {formatAmount(order.amount, order.currency)} ({order.status})
{#if order.status === 'pending'}
<form method="POST" action="?/cancel" use:enhance>
<input type="hidden" name="id" value={order.id} />
<button>Cancel</button>
</form>
{/if}
</li>
{/each}
</ul>A few things worth noting:
loaduses thefetchfrom its argument, not the globalfetch. It carries the user's cookies, resolves relative URLs, and during server rendering can inline the response into the page so the browser does not request it again.- The form works without JavaScript.
<form method="POST" action="?/cancel">is an ordinary HTML form posting to thecancelaction; withuse:enhance, when JavaScript is available it submits in the background instead of reloading the whole page. The data returned byfail(400, ...)appears inform, and the response status is 400 as well. - Amounts follow the series' convention of integers in minor units, converted only for display.
formatAmountlives insrc/lib/money.ts; Step 7 gives it a test.
If the data a load needs is public anyway and involves no secrets, it can go in a universal +page.ts. For example, a page that checks service status:
// src/routes/status/+page.ts
import type { PageLoad } from './$types';
// Universal load: runs on the server first, then in the browser; never put secrets here
export const load: PageLoad = async ({ fetch }) => {
const res = await fetch('/api/health');
return { health: (await res.json()) as { ok: boolean } };
};The /api/health it calls is a +server.ts endpoint:
// src/routes/api/health/+server.ts
import type { RequestHandler } from './$types';
export const GET: RequestHandler = () => Response.json({ ok: true });| Where | Good for | Not good for |
|---|---|---|
+page.server.ts | Calls with a token, database or internal-network access; handling form writes | Merely relaying public data when you want to skip a server hop |
+page.ts | Public data, or returning things that cannot be serialised (such as components) | Any request that involves a secret |
+server.ts | JSON endpoints for other programs, webhooks, file downloads | Data used only by your own pages (just use load) |
The full flow of a request
Figure: on the first load the server runs load and produces complete HTML; the browser shows it first, then downloads JavaScript and completes hydration. When the user later clicks a link, the browser asks the server only for data and updates the page in place.
Hydration means this: the HTML sent by the server is already drawn, but the buttons do not work yet; once the browser downloads the JavaScript, it "attaches" events and state to that existing HTML, and only then is the page truly interactive. During that window the user can already see the content but cannot use it.
Step 5: Rendering modes and adapters
Three rendering modes
Figure: with SSR the server builds complete HTML on every request; with CSR only an empty shell is sent and the content appears once JavaScript has run; with prerendering the HTML file was produced at build time and is sent straight away. All three finish with hydration once the JavaScript loads (unless CSR is turned off).
- SSR (server-side rendering): on every request the server runs
loadand the components and produces complete HTML. This is SvelteKit's default. The content is fresh and visible to search engines, but you need a server (or edge function) that can run code. - CSR (client-side rendering): the browser receives almost blank HTML and draws the content after downloading JavaScript. By default SvelteKit follows SSR with CSR (that is, hydration and later navigation). Setting
export const ssr = falseskips server rendering entirely and sends only the shell. - Prerendering: the page is run at build time and saved as an HTML file. Requests are answered with the file directly: fastest and cheapest, but the content only changes at the next build.
These are controlled with page options in +page.ts, +page.server.ts or +layout.ts; in a layout they apply to every page below it:
// src/routes/+page.ts
// The home page content is fixed, so output it as HTML at build time
export const prerender = true;| Option | Effect | Good for | Not good for |
|---|---|---|---|
| Default (SSR + CSR) | Complete HTML first, then navigation in the browser | Most pages: order lists, account pages | Pages whose content barely changes (wastes the server) |
prerender = true | HTML file produced at build time | Home page, documentation, articles | Content that differs per user, or pages with form actions |
ssr = false | Only a shell is sent; everything drawn in the browser | Tool pages relying on browser APIs, internal-only editors | Pages that must be indexed, or must show quickly on slow networks |
csr = false | No JavaScript at all, pure HTML | Pages with no interaction (terms, plain text) | Any page with buttons, filters or use:enhance |
Prerendering has two limits to remember: a page with form actions cannot be prerendered (a POST needs a server to handle it); and for dynamic routes (such as /orders/[id]) the build must be able to find every URL, either because a prerendered page links to them or because you list the parameters with entries.
Adapters: one codebase, different build outputs
Figure: vite build first produces a generic intermediate result, and the adapter then reshapes it for the target platform: a folder of static files, Cloudflare's _worker.js plus static assets, or a Node.js server.
SvelteKit itself does not know where you will deploy. An adapter is the last step of the build: it turns the generic build output into something a particular platform can run. Changing platform usually means only changing the adapter; routes and components stay the same.
| Situation | Rendering | Adapter | Why |
|---|---|---|---|
| All content can be decided at build time (docs, blogs) | Prerender everything | @sveltejs/adapter-static | The output is a folder of files for any static host or CDN |
Back office or storefront needing server load and form actions | SSR + some prerendering | @sveltejs/adapter-cloudflare | Server code runs at Cloudflare's edge, static files go through the CDN |
| You already have hosts or Kubernetes and want a long-running process | SSR + some prerendering | @sveltejs/adapter-node | The output is a Node.js server that can be packaged as a container |
| Just trying things out, platform not decided | Depends on the page | @sveltejs/adapter-auto | Picks an adapter automatically on supported platforms; name one explicitly for real projects |
shop-admin uses adapter-cloudflare, because the orders page must call api-gateway with a token on the server, which a static adapter cannot do. If you switch to adapter-static, the root +layout.ts must contain export const prerender = true, and every page must be prerenderable or the build fails, which conveniently catches pages that "accidentally depend on a server".
The last lines of npm run build tell you which adapter was used, and the output lands in .svelte-kit/cloudflare, as set in wrangler.jsonc:
> Using @sveltejs/adapter-cloudflare
✔ done.svelte-kit/cloudflare/
├── _app/ compiled JavaScript and CSS (hashed file names, cacheable long term)
├── _worker.js server-side code (load, actions, +server.ts)
├── _routes.json which paths go to _worker.js and which are served as static files
├── _headers
├── index.html the prerendered home page
├── 404.html
└── robots.txtStep 6: Environment variables and secrets
In SvelteKit 3, environment variables are first declared in src/env.ts and then imported from one of two modules:
$app/env/private: the default. It can be imported only by server-side code, and its values never reach the browser's JavaScript.$app/env/public: a variable appears here only if it is declared withpublic: true. The browser can see it, so it may hold only public values.
// src/env.ts
import { building } from '$app/env';
import { defineEnvVars } from '@sveltejs/kit/env';
// Secrets may be missing while building (in CI) but are required when the server starts
const required = (value: string | undefined) => {
if (!value && !building) throw new Error('required');
return value ?? '';
};
export const variables = defineEnvVars({
API_GATEWAY_URL: { schema: required, description: 'Internal URL of api-gateway' },
ADMIN_API_TOKEN: {
schema: required,
description: 'Token the back office uses to call api-gateway'
},
SHOP_NAME: { public: true, schema: (value) => value || 'Shop admin' }
});A few rules:
- Variables are private and read at run time by default. Adding
static: truewrites the value into the code at build time, which suits feature switches and lets unused code be dropped from the bundle; never usestaticfor secrets, or they travel with the build output. schemadoes the validation. You can use a library such as Valibot or Zod, or write a function as above. When a value is invalid, the app fails to start (or to build), which is much better than discovering an empty token after going live. Above,buildinglets the CI build run without a real token.- Whether a variable is public is declared with
public: true, not by a prefix on its name. - SvelteKit blocks leaks. Importing
$app/env/privatein+page.sveltefails the build outright:
SvelteKit error: server_only_import
Cannot import `$app/env/private` into code that runs in the browser, as this could leak sensitive information.For local development, put the values in .env (the .gitignore generated by sv already excludes it); when deploying to Cloudflare Pages, use npx wrangler pages secret put ADMIN_API_TOKEN --project-name=shop-admin, or add an encrypted variable in the Pages project's settings. The older modules such as $env/static/private are deprecated and scheduled for removal in SvelteKit 4; do not use them in new code.
Step 7: Testing and checks
A project created by sv already has three commands, and CI runs them in order:
| Command | What it does | What it catches |
|---|---|---|
npm run check | svelte-check: TypeScript and Svelte type and syntax checks | Type errors, old syntax, imports of missing modules, accessibility warnings |
npm test | Vitest unit tests | Errors in pure logic (amount conversion, filter conditions) |
npm run build | A real build, including prerendering and the adapter | Leaked server modules, prerender failures, adapter misconfiguration |
Pure logic moved into ordinary .ts files in src/lib/ is the easiest to test:
// src/lib/money.ts
// Amounts are always integers in minor units (1999 means 19.99), converted only for display
export function formatAmount(minor: number, currency: string, locale = 'zh-TW'): string {
if (!Number.isSafeInteger(minor)) throw new Error('amount must be a safe integer');
const fmt = new Intl.NumberFormat(locale, { style: 'currency', currency });
const digits = fmt.resolvedOptions().maximumFractionDigits ?? 0;
return fmt.format(minor / 10 ** digits);
}// src/lib/money.spec.ts
import { describe, expect, it } from 'vitest';
import { formatAmount } from './money.ts';
describe('formatAmount', () => {
it('converts minor units to a display amount', () => {
expect(formatAmount(1999, 'USD', 'en-US')).toBe('$19.99');
expect(formatAmount(500, 'JPY', 'en-US')).toBe('¥500');
});
it('rejects amounts that are not safe integers', () => {
expect(() => formatAmount(19.99, 'USD')).toThrow();
});
});Let Intl.NumberFormat decide the number of decimal places for each currency (two for US dollars, none for yen) rather than hard-coding a division by 100. The series stores amounts as int64, while a JavaScript number is exact only up to 2^53, so the function checks Number.isSafeInteger first and fails loudly outside that range instead of quietly computing the wrong value.
To test complete flows such as "open the page, click a button, see the result", use Playwright end-to-end tests (npx sv add playwright). They are slower than unit tests and more sensitive to the environment, so use them to guard a few of the most important paths (signing in, viewing orders, cancelling an order), not to test every edge case.
Step 8: Working with AI skills
“Getting More from AI Agent Skills: Choosing, Writing and Chaining Them into a Workflow” already explains what a skill is, how to write its description and how to chain skills into a workflow. This step covers only what is specific to a SvelteKit project.
Why front-end projects need it in particular
A model's training data contains a great deal of Svelte 3 and 4 and SvelteKit 1 and 2 code. Without the project's rules, it often writes:
| Old syntax models often write | SvelteKit 3 / Svelte 5 syntax | What happens in a new project |
|---|---|---|
export let step = 1 | let { step = 1 } = $props() | Compile error (runes mode) |
$: doubled = count * 2 | let doubled = $derived(count * 2) | Compile error (runes mode) |
on:click={...} | onclick={...} | Compile error (runes mode) |
import ... from '$lib/money' | import ... from '#lib/money.ts' | svelte-check cannot find the module |
import ... from '$env/static/private' | Declare in src/env.ts, import from $app/env/private | Module not found in this project; deprecated even where it works |
Adding svelte.config.js | Configure sveltekit() in vite.config.ts | No longer supported in SvelteKit 3 |
import { page } from '$app/stores' | import { page } from '$app/state' | Module removed |
The good news is that most of these mistakes are caught by npm run check or npm run build. So AI collaboration comes down to two things: tell it the right syntax from the start, and require it to run the checks before it says "done".
When a skill enters the AI's context
Figure: the project's CLAUDE.md and every skill's name and description are present in every session; only when a request matches a skill's description is the full text of its SKILL.md loaded; reference files mentioned by SKILL.md are read only when they are needed.
This "load only when needed" design decides where each piece of content belongs:
| Where | What goes there | Why |
|---|---|---|
CLAUDE.md (or AGENTS.md) | A one-line project summary, common commands, folder conventions, "run check / test / build before finishing" | Loaded every time, so keep it short and only rules that always apply |
| A project skill (e.g. adding a page) | Steps, examples and completion criteria for one kind of task | Loaded only for that kind of task, so it can be detailed |
| The official Svelte skills and MCP | Current Svelte 5 and SvelteKit docs, automatic syntax checks | Maintained upstream and updated with each version |
Official AI tooling
The Svelte team maintains a set of AI tools you can use directly, rather than curating the docs yourself:
- MCP server: the remote URL is
https://mcp.svelte.dev/mcp; in Claude Code you can add it withclaude mcp add -t http -s project svelte https://mcp.svelte.dev/mcp. It provides four tools:list-sections,get-documentation(fetches the current docs),svelte-autofixer(static analysis of generated Svelte code, which can be run repeatedly until no issues remain) andplayground-link. - Skills:
svelte-code-writerandsvelte-core-bestpractices, installable withnpx skills add sveltejs/ai-tools --skill <name>, and also included in the official Claude Code plugin (/plugin marketplace add sveltejs/ai-tools, then/plugin install svelte). - llms.txt:
https://svelte.dev/llms.txtlists versions of the docs written for language models, includingllms-full.txt(complete),llms-medium.txtandllms-small.txt(compressed), and per-package versions such as/docs/kit/llms.txt. Useful for tools that do not support MCP. sv add ai-tools: ansvadd-on that writes.mcp.json, anAGENTS.md(explaining how to use the MCP tools) and the official skills under.claude/skills/into the project in one go.
The official tools cover "how to write Svelte". "How to write this project" (which adapter, how to call the API, how to handle money, what counts as done) is still yours to write.
Project rules and an "add a back-office page" skill
CLAUDE.md holds only short rules that always apply:
# shop-admin
The shop back office (SvelteKit 3, Svelte 5, TypeScript), deployed to Cloudflare Pages.
## Commands
- npm run dev: dev server
- npm run check: types and syntax
- npm test: unit tests
- npm run build: build (including prerendering and the adapter)
## Rules
- Use only Svelte 5 runes and SvelteKit 3 syntax; when unsure, look it up with the Svelte MCP docs first
- Call api-gateway only through src/lib/server/gateway.ts
- Before saying "done", check, test and build must all pass, with the output pasted
- Do not deploy, do not push to main, do not edit .github/workflows/Adding a page is the task most often handed to AI, and its steps are fixed, so it suits a skill in .claude/skills/add-admin-page/SKILL.md:
---
name: add-admin-page
description: Add or change a page in shop-admin, including the route, load, form actions and tests. Use when the user says "add a page", "new back-office feature" or "change the order list".
---
# Add a back-office page
## First decide where the data comes from
- Needs a token or writes data → `+page.server.ts` (load and actions)
- Public data, no secrets → `+page.ts`
- JSON for other programs → `+server.ts`
- Content known at build time → add `export const prerender = true`
## Syntax
- Components: `$props()`, `$state`, `$derived`, `onclick`; never `export let`, `$:`, `on:click`
- Imports: `#lib/...` with the file extension; never `$lib`
- Environment variables: declare in `src/env.ts`, import from `$app/env/private` or `$app/env/public`; never `$env/*`
- Calling api-gateway: only through `gateway()` in `#lib/server/gateway.ts`
- Money: integers in minor units, displayed with `formatAmount`
- After writing a `.svelte` file, run the Svelte MCP `svelte-autofixer` until it reports no issues
## Done means
1. New pure logic lives in `src/lib/` with a `*.spec.ts` next to it
2. `npm run check`, `npm test` and `npm run build` all pass
3. Open the new page with `npm run dev` and attach screenshots at desktop and phone widths
4. Report which files changed and what was not verified
## Do not
- Do not edit `.github/workflows/`, `wrangler.jsonc` or existing variables in `src/env.ts`
- Do not run `wrangler pages deploy`; do not read or print `.env`From request to PR
Figure: the request triggers the skill, the agent writes code to the conventions and runs the checks, tests and build, going back to fix failures; once everything passes it opens a PR, a person reviews and merges it, and CI handles deployment.
In this flow the AI does not touch deployment. It can write code, run checks and open a PR; merging and deploying are decided by people and CI. The reasons are practical:
- No deploy token for the AI. The Cloudflare token lives only in GitHub secrets, so a local agent cannot get it and therefore cannot deploy by mistake.
- No pushing to main. Branch protection rules that require a PR and passing checks before merging mean the agent could not push even if it tried; permission settings can also deny deployment commands.
- The agent attaches screenshots; a person looks at them. Passing type checks does not mean the screen is right; a broken layout or horizontal scrolling at phone width only shows up when you look. The PR preview URL (Step 9) lets reviewers see it without running anything locally.
Step 9: Deploying automatically to Cloudflare Pages with GitHub Actions
Understand CI/CD first
Figure: a push or PR triggers CI (check, test, build); once it passes, CD deploys the build output: a PR gets a preview URL and main updates the production site; when something breaks, production is switched back to the previous deployment.
- CI (continuous integration): every push automatically runs the checks, tests and build. The goal is "broken code cannot get into main".
- CD (continuous deployment): once CI passes, the build output is deployed automatically. The goal is "main always equals what is live", rather than relying on someone building and uploading from their own machine.
- Preview deployments: every PR is deployed to its own URL so reviewers can click through without affecting production.
- Rollback: when a new version has a problem, switch back to the last deployment known to be good.
Two ways to connect
Cloudflare Pages offers two ways to deploy from GitHub:
| Approach | How it works | Good for | Not good for |
|---|---|---|---|
| Cloudflare's Git integration | Authorise Cloudflare to read the repo; Cloudflare builds and deploys | Going live fastest, with no need to run your own checks first | Enforcing check / test before deploying, or sharing build steps with other CI |
| GitHub Actions + Direct Upload (this article) | Check and build in GitHub Actions, then upload the output with wrangler pages deploy | Running full checks before deploying; seeing checks and deploys in one pipeline | Not wanting to maintain a workflow file; nobody on the team knows GitHub Actions |
Note that a Pages project created with Direct Upload cannot later be switched to Git integration, and going the other way also means a new project. So choose at the start. This article uses GitHub Actions because we require "check, test and build all pass before deploying", and we want that rule written in the repo where it can be reviewed.
One-off setup
1. Create the Pages project. Log in once on your machine (npx wrangler login), then create the project and name its production branch:
npx wrangler pages project create shop-admin --production-branch=main
npx wrangler pages secret put API_GATEWAY_URL --project-name=shop-admin
npx wrangler pages secret put ADMIN_API_TOKEN --project-name=shop-admin--production-branch=main means a deployment with --branch=main is production, and every other branch name is a preview. Pages variables and secrets are split into production and preview environments; you can check what each side has under the project's Settings → Variables and Secrets. The preview environment should point at a test api-gateway and token.
2. Create an API token that can only deploy Pages.
Figure: schematic; the actual labels may change as Cloudflare updates its dashboard. ① On the API Tokens page of the dashboard, click Create Token and choose a custom token; ② grant only Account / Cloudflare Pages / Edit; ③ limit the resources to this one account; ④ review the summary and create it. The token is shown only this once, so copy it straight away.
The smaller the token's permissions the better: it only needs to "deploy Pages", not DNS, Workers or other accounts. If it leaks, the damage is limited to this account's Pages. You can also set an expiry date as a reminder to rotate it. The account ID is shown in the API section on the right of a domain's overview page, or by running npx wrangler whoami locally; it is not a secret, but keeping it in secrets alongside the token is tidier.
3. Put the token into GitHub secrets.
Figure: schematic. ① The repo's Settings; ② Secrets and variables → Actions under Security in the sidebar; ③ New repository secret on the Secrets tab; ④ enter the name CLOUDFLARE_API_TOKEN and the value, then click Add secret; repeat for CLOUDFLARE_ACCOUNT_ID.
Once saved, the value is never shown again and is masked in workflow logs. Note that PRs from forks do not receive secrets (GITHUB_TOKEN is the only exception), so the workflow below skips deployment for fork PRs and only runs the checks.
4. Commit worker-configuration.d.ts to the repo. Both npm run check and npm run build first run wrangler types --check to make sure the types file is up to date; without the file, CI fails. After changing wrangler.jsonc, rerun npm run gen and commit the result.
The workflow file
.github/workflows/deploy.yml:
name: ci-deploy
on:
push:
branches: [main]
pull_request:
# A new push to a PR cancels the older run; main queues instead, so a deployment is never cut off halfway
concurrency:
group: deploy-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 24
cache: npm
- run: npm ci
- run: npm run check
- run: npm test
- run: npm run build
- uses: actions/upload-artifact@v7
with:
name: site
path: .svelte-kit/cloudflare
include-hidden-files: true
retention-days: 7
deploy:
needs: verify
# PRs from forks get no secrets, so skip deployment for them
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
permissions:
contents: read
deployments: write
steps:
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
with:
name: site
path: .svelte-kit/cloudflare
- id: deploy
uses: cloudflare/wrangler-action@v4
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy .svelte-kit/cloudflare --project-name=shop-admin --branch=${{ github.head_ref || github.ref_name }}
- name: Write down the URLs
env:
URL: ${{ steps.deploy.outputs.deployment-url }}
ALIAS: ${{ steps.deploy.outputs.pages-deployment-alias-url }}
run: |
echo "### Deployed" >> "$GITHUB_STEP_SUMMARY"
echo "- This deployment: $URL" >> "$GITHUB_STEP_SUMMARY"
echo "- Branch URL: $ALIAS" >> "$GITHUB_STEP_SUMMARY"Why each part is written this way:
on: a push to main is a production deployment;pull_requestmakes every PR run the checks and get a preview URL.concurrency: only one run per branch at a time. If a PR is pushed three times in a row, only the last push matters, so older runs are cancelled; main is not cancelled, to avoid cutting a deployment off halfway, and the new run queues until the previous one finishes.permissions: read-only by default, withdeployments: writeadded only for the deploy job. The workflow'sGITHUB_TOKENshould have minimal permissions too.- Two jobs:
verifyinstalls packages, checks, tests and builds, and never sees the Cloudflare secrets;deployonly downloads the build output and uploads it.npm ciruns packages' install scripts, so keeping it on a different machine from the step that holds the token means a compromised package cannot get the token. The cost is the time spent uploading and downloading the artefact. npm ci, notnpm install: it installs strictly frompackage-lock.json, so versions match your machine, and it fails outright if the lock file andpackage.jsondisagree.cache: npmcaches downloaded packages to speed up later runs.include-hidden-files: true: the output sits in.svelte-kit/, a folder whose name starts with a dot, so it is safer to enable this explicitly.--branch: on a PR,github.head_refis the PR's source branch, so it deploys as a preview; on a push to main,head_refis empty andgithub.ref_name(main) is used instead, so it deploys to production.- Recording the URLs:
wrangler-actionoutputsdeployment-url(the unique URL of this deployment) andpages-deployment-alias-url(the branch alias URL), and we write them into the job summary, visible at the top of the run page in Actions. The URLs reach the shell throughenvrather than being written as${{ }}directly insiderun, a habit that avoids command injection.
What a run looks like
Figure: schematic. ① The repo's Actions tab lists every run; ② opening a run shows the verify and deploy jobs and their dependency; ③ expanding a job shows each step, and a failed step is marked and its log opened; ④ the summary area of the run page lists the deployment URL and the branch URL.
A PR has two kinds of preview URL:
- This deployment's URL:
<hash>.shop-admin.pages.dev, different for every deployment and always pointing at that particular build. - The branch alias:
<branch-name>.shop-admin.pages.dev, always pointing at the latest deployment of that branch. Characters in the branch name that are not letters or digits become hyphens, sofix/order-filterbecomesfix-order-filter.
Preview URLs are public by default; responses only carry X-Robots-Tag: noindex so search engines do not index them. A preview of the back office also calls api-gateway, so do two things: enable Cloudflare Access for preview deployments in the Pages project's settings so only team members can see them, and point the preview environment's API_GATEWAY_URL and token at a test environment rather than testing with production data.
Step 10: Rolling back, and comparing ways to deploy
How to roll back when something breaks
There are two routes back, with different purposes:
Figure: schematic. ① Open Deployments in the Pages project; ② under All deployments, find the last good production deployment and open the "⋯" menu on its right; ③ choose Rollback to this deployment; ④ after confirming, production switches immediately.
| Approach | Speed | Good for | Watch out for |
|---|---|---|---|
| Rollback in the Pages dashboard | Immediate | Stopping the bleeding when production breaks | Only successfully built, undeleted production deployments qualify; previews are not valid targets; the code on main is still broken |
git revert and push to main | Minutes | You know which commit is at fault and want code and production to match | It runs the whole CI; it must happen before the next push to main, or the broken code is deployed again |
In practice you use both: roll back in the dashboard to stop the damage, then git revert to fix main. Doing only the first means the next merged PR redeploys the broken version; doing only the second means waiting for CI before recovery. For the details of git revert and tags, see “Versioning with Git: Branches, Tags and Rolling Back”.
Also remember: a rollback only swaps the code. If the new version also changed the api-gateway API contract or a data format, the rolled-back front end may no longer match the back end. When the front end and back end deploy separately, the API must stay backward compatible; this is the same "old and new versions running side by side" problem discussed in “Blue-Green and Canary Releases: Doing Them Right and What to Watch For”.
Comparing three ways to deploy
| Approach | How it works | Good for | Why | Not good for |
|---|---|---|---|---|
| Cloudflare Pages + GitHub Actions (this article) | adapter-cloudflare; CI builds, then wrangler pages deploy uploads | Small and medium back offices, storefronts, content sites; teams that do not want to run servers | No hosts to maintain; PR previews and one-click rollback built in; static files served by the CDN | Long-running jobs; databases reachable only on an internal network that cannot be exposed; specific native Node.js modules |
Your own VM (adapter-node, or static files + rsync) | Copy the output to the host and run a Node.js server with systemd or PM2, or serve static files with nginx | You already have hosts and operational habits; you need to sit on the same network as internal services | Full control of the environment, fixed cost | Nobody owns security updates and monitoring for the host; you want preview environments and fast rollback without building them yourself |
| Docker + Kubernetes / Argo CD | Package adapter-node as an image; Argo CD syncs the cluster from config in Git | The company already runs all its services on Kubernetes (like the series' shop back end) | Same deployment, monitoring, canary releases and access control as the back end | A single front-end site with no existing cluster: setting up Kubernetes just for it does not pay off |
A one-line way to choose: with no existing platform, use a managed service such as Pages; if you already have Kubernetes, put it there alongside the back end; with just one host, use rsync for a static site and adapter-node only when you need server rendering. Cloudflare also offers deployment with Workers plus static assets, which has more features than Pages, and sv's adapter options include a matching setting; when choosing between the two for a new project, start with Cloudflare's own comparison.
Common pitfalls
Writing code from old tutorials or AI output. svelte.config.js, $lib, $env/static/private, export let, on:click and $app/stores are no longer correct in SvelteKit 3 and runes mode. Let npm run check be the gatekeeper, and state the right versions clearly in CLAUDE.md and the skill.
Putting secrets in a universal load or a public variable. +page.ts is bundled for the browser; values with public: true or static: true appear in the code. Read secrets only from $app/env/private, and use them only in *.server.ts or src/lib/server/.
Using the global fetch instead of the fetch from load's argument. On the server the global fetch does not carry the user's cookies and cannot use relative URLs, and data fetched during server rendering gets fetched again by the browser.
Syncing state with $effect. "When a changes, set b to a * 2" should be written with $derived. Using $effect adds an extra update and makes infinite loops easy to write.
Assuming prerendered pages update themselves. A page with prerender = true is produced only at build time; when the data changes you must redeploy to see it. Do not prerender data that changes, or fetch it separately in the browser.
Needing real secrets to build in CI. If src/env.ts requires the token at build time, CI has to hold the production token. Use building so the build can run without the value and validation happens at run time; the secret then needs to live only in Cloudflare.
Not committing worker-configuration.d.ts or package-lock.json. The first makes wrangler types --check fail, the second makes npm ci fail. Both belong in version control.
Preview URLs are public. A back-office preview connected to the production api-gateway amounts to putting an unprotected back office on the internet. Protect previews with Cloudflare Access and point them at a test environment.
Rolling back only in the dashboard and forgetting main. The next merge redeploys the broken version. git revert straight after rolling back.
Giving the token too much. Creating a token from a broad template such as "Edit all resources" is convenient, but a leak then affects the whole account. Grant only Cloudflare Pages Edit, and limit it to the account.
Key takeaways
- Svelte is the component compiler; SvelteKit is the application framework (routing, data loading, rendering modes, adapters), with Vite for development and bundling. It suits back offices, content sites and apps that need server rendering; a single page with almost no interactivity, or a team deeply invested in React, need not switch.
- Folders under
src/routes/are URLs;+page.svelteis the screen,+page.tsthe universalload,+page.server.tsthe serverloadand form actions,+server.tsan API endpoint. In SvelteKit 3 the configuration lives invite.config.ts, and shared code is imported as#lib/.... - Svelte 5 uses
$state,$derived,$effect,$propsandonclick; when$derivedwill do, do not use$effect. - Code with
.serverin its name or undersrc/lib/server/runs only on the server; calls toapi-gatewaywith a token always go there. Universalloadruns in the browser too. - The default is SSR plus hydration plus browser navigation; use
prerenderfor fixed content; an adapter turns the same code into static files, Cloudflare output or a Node.js server. - Environment variables are declared in
src/env.tsand secrets read from$app/env/private; importing them into browser code fails the build. npm run check,npm testandnpm run buildare the three gates for every change and every CI run; add Playwright for the important flows.- AI collaboration:
CLAUDE.mdholds short rules that always apply, a skill holds the steps and completion criteria for one kind of task, and the official Svelte MCP and skills supply current syntax; the AI writes code, runs the checks and opens PRs, but never holds deploy tokens or pushes to main. - Automatic deployment: GitHub Actions checks and builds,
wrangler-actionuploads to Cloudflare Pages; PRs get preview URLs and main updates production; the token has only Pages Edit, lives in GitHub secrets, and is kept apart from the job that installs packages. - Roll back with Pages' Rollback to stop the damage, then
git revertto fix main; with no existing platform use a managed service, and with Kubernetes already in place deploy alongside the back end.
References
- What are runes? (official Svelte documentation): Svelte 5 runes such as
$stateand$derived, used in step 3. - Routing (official SvelteKit documentation): filesystem routing and the
+page/+layoutfiles in step 2. - Loading data (official SvelteKit documentation): where universal and server
loadfunctions run, used in step 4. - Page options (official SvelteKit documentation): the
prerender,ssrandcsroptions behind the rendering modes in step 5. - Adapters (official SvelteKit documentation): one codebase producing different build outputs per adapter, used in step 5.
- $env/static/private (official SvelteKit documentation): environment variables that can only be read on the server, used in step 6.
- Tools (official Svelte AI documentation): the four tools of the Svelte MCP server listed in step 8.
- Use Direct Upload with continuous integration (official Cloudflare Pages documentation): deploying to Pages from GitHub Actions with
wrangler-action, used in step 9.
Next
The back office now deploys itself, PRs get preview URLs, and a bad release can be rolled back in one click. The next article, “Bonus: Building a Telegram Bot, and How Best to Pair It with a Mini App”, opens a Telegram entrance to the shop: a bot handles notifications and order lookups, the shopping screens become a Mini App built with the SvelteKit covered here, and the Go backend verifies who the user is.