Svelte 73 ๐งก SPA Mode and Static Site Generation (SSG)
SvelteKit is primarily known for its server-side rendering capabilities, but it is architecturally designed to be adaptable. You can strip away the server requirements to deploy your application as a pure Single-Page Application (SPA) or generate a fully static version of your site that requires no server-side logic at runtime. These modes are essential for hosting on low-cost static infrastructure like AWS S3, Cloudflare Pages, or GitHub Pages.
Switching to these modes involves two distinct steps: configuring the component lifecycle via ssr and prerender exports, and choosing the correct adapter. By understanding how to transform your application from a dynamic server-rendered experience into a static asset collection, you gain the ability to choose the perfect deployment strategy for every project, from high-traffic marketing sites to complex client-side applications.
Key point: SPA mode is achieved by disabling SSR (ssr = false), while Static Site Generation (SSG) is achieved by pre-rendering routes and using adapter-static to output pure HTML/JS/CSS files instead of a Node.js server.
Why exists
The hosting cost problem. Server-rendered applications require a Node.js runtime, which incurs costs for compute power. SSG and SPA modes allow you to host on “serverless” or object storage services, which are often free or significantly cheaper.
The portability requirement. Some environments, such as browser extensions, offline-first apps, or hardware-constrained environments, do not have access to a Node.js server. Pure SPA mode allows SvelteKit to run in any browser environment.
The performance trade-off. Pre-rendering (SSG) eliminates the time spent on server-side computation. For content that doesn’t change frequently, delivering a static file via a global CDN provides the fastest possible load times.
The static hosting simplification. Many developers prefer the simplicity of a static build pipeline. SSG workflows allow for atomic deploymentsโyou build your site, upload the files, and it is instantly live without managing server processes or environment variables at runtime.
The decoupling requirement. By using an SPA or SSG mode, you decouple the frontend deployment from the backend. The frontend becomes a collection of static assets, allowing you to iterate on the UI without needing to restart a server or deal with deployment downtime.
a. Configuring SPA Mode
SPA mode is useful when your application depends heavily on client-side state or browser APIs that are unavailable during SSR. By setting ssr = false in your root +layout.js, you tell SvelteKit to skip the server-side rendering phase and deliver a base shell that hydrates on the client.
// src/routes/+layout.js
export const ssr = false; // Disable SSR globally
export const prerender = true; // Still pre-render the shell
In this mode, SvelteKit delivers a single index.html file and your JS bundles. When the browser loads the page, Svelte takes over to render the UI. This is ideal for dashboards, admin panels, or any tool where SEO is not a priority and the app lives behind an authentication wall.
b. Static Site Generation (SSG)
SSG works by executing your load functions at build time and serializing the results into static HTML files. To deploy this, you must install @sveltejs/adapter-static. This adapter replaces the default Node-based adapter, turning your build output into a simple directory of files.
// svelte.config.js
import adapter from '@sveltejs/adapter-static';
export default {
kit: {
adapter: adapter({
pages: 'build',
assets: 'build',
fallback: '404.html' // or 'index.html' for SPA mode
})
}
};
When using adapter-static, every page that can be pre-rendered will be. If you have dynamic routes (e.g., [id]), you must explicitly tell SvelteKit which IDs to generate using the entries function in your +page.js or +layout.js files.
c. The “SPA Static” Hybrid
You can combine the two: a fully static application that behaves like an SPA. By setting ssr = false and configuring adapter-static with a fallback page, SvelteKit generates a static index.html that acts as the entry point for all routes. The client-side router then handles navigation, bypassing the server entirely.
// svelte.config.js
adapter({
pages: 'build',
fallback: 'index.html' // Essential for SPA routing
})
This setup is the standard for static-hosted applications. The fallback: 'index.html' setting ensures that when a user refreshes the page on a deep route like /dashboard/settings, the browser returns index.html, which then loads the JS bundles that correctly route the user back to the settings page.
Complete Example Session
// ============================================
// PART 1: CONFIGURING THE ADAPTER
// ============================================
// svelte.config.js
import adapter from '@sveltejs/adapter-static';
export default {
kit: { adapter: adapter({ fallback: 'index.html' }) }
};
// ============================================
// PART 2: GLOBAL SPA SETTINGS
// ============================================
// src/routes/+layout.js
export const ssr = false;
export const prerender = true;
// ============================================
// PART 3: DEFINING PRERENDER ENTRIES
// ============================================
// src/routes/blog/[slug]/+page.js
export async function entries() {
return [{ slug: 'hello-world' }, { slug: 'svelte-tips' }];
}
export const prerender = true;
// ============================================
// PART 4: THE FALLBACK PAGE
// ============================================
// If a user hits a route not in entries,
// they get index.html and SPA mode takes over.
These parts show the standard configuration flow: selecting the static adapter, disabling server-side rendering, and providing entry points for the static generation engine.
Quick Reference
Mode Configuration
| Setting | SPA Mode | SSG Mode |
|---|---|---|
ssr | false | true (or false) |
prerender | true | true |
| Adapter | adapter-static | adapter-static |
| Fallback | index.html | Not required |
Best Practices
โ Do This:
// Use fallback for pure SPA deployment
fallback: 'index.html' // โ
// Always define entries for dynamic routes in SSG
export function entries() { return [...] } // โ
// Disable SSR for client-heavy apps
export const ssr = false; // โ
โ Don’t Do This:
// Don't use Node-specific APIs in SPA mode
import { fs } from 'node:fs'; // โ
// Don't leave fallback undefined in SPA static mode
// (users will get 404s on deep links) // โ
// Don't use SSR features like event.cookies in SPA
cookies.set('key', 'val'); // Fails in browser // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| 404 on Refresh | Fallback not configured | Set fallback: 'index.html' |
| Hydration Mismatch | SSR/Client rendering conflict | Set ssr = false |
| Missing Routes | Build doesn’t know route IDs | Implement entries function |
| Secret Leakage | Using process.env in SPA | Use $env/static/public |
Real-World Examples
1. Cloudflare Pages Setup
adapter({ fallback: '404.html' })
2. Static Blog
export const prerender = true;
3. Client-Only Dashboard
export const ssr = false;
4. Defining Static Routes
export function entries() { return [{id: '1'}, {id: '2'}]; }
5. Fallback for Single Page Apps
adapter({ fallback: 'index.html' })
6. Disabling Pre-render for Dynamic Routes
export const prerender = false;
7. Build Output Dir
adapter({ pages: 'dist' })
8. SPA Layout
export const ssr = false;
9. Static Assets
adapter({ assets: 'public' })
10. API-Driven SSG
// Fetch list from external API
export async function entries() {
const res = await fetch('...');
return await res.json();
}
Visual
SPA vs SSG Workflow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SPA MODE โ SSG MODE โ
โ โโโโโโโโโโโโโโโโโโโโ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ index.html โ โ โ /about/index.html โ โ
โ โ (shell) โ โ โ /blog/post-1/index.html โ โ
โ โโโโโโโโโโโโโโโโโโโโ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ Routing: Client-side โ Routing: Static files โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The SPA Fallback Mechanism
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Request: /dashboard/profile โ
โ โ โ
โ โผ โ
โ Check File System (404) โ
โ โ โ
โ โผ โ
โ Return index.html (Fallback) โ
โ โ โ
โ โผ โ
โ JavaScript Hydrates โโโบ Route to /dashboard/profile โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Adapter | adapter-static |
| SPA Setting | ssr: false |
| SSG Setting | prerender: true |
| Entry Point | index.html (for SPA fallback) |
| Runtime | Browser-only (for SPA mode) |
Key takeaways:
- Adapters dictate deployment.
@sveltejs/adapter-staticis mandatory for both SPA mode and SSG deployment. ssr = falsecreates a client-only app. Use this when your application logic is browser-exclusive or when you want to minimize server dependencies.- Pre-rendering (SSG) is build-time processing. Use it to generate static HTML files for high performance and zero-cost hosting.
- The fallback strategy is critical. If you are building a static SPA, always define a fallback HTML page so that deep links return the app shell rather than a server 404.
- Define route entries. For SSG, SvelteKit needs to know which pages to generate; use the
entriesfunction for dynamic route slugs.
Remember: SPA and SSG modes turn SvelteKit into a powerful static site generator and application builder. By carefully selecting your ssr and prerender settings and correctly configuring adapter-static, you can build applications that are incredibly fast, inexpensive to host, and highly portable across the web.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!