SvelteKit 01 🧡 Introduction & Setup — Creating a SvelteKit project with sv CLI, svelte.config.js, and directory conventions
SvelteKit is the official application framework for Svelte, designed to handle routing, server-side rendering (SSR), static site generation (SSG), and API endpoint creation in a unified environment. Unlike simple Svelte projects, SvelteKit is built for production-grade web applications that require database integration, authentication, and optimized performance. It leverages Svelte’s reactive compiler to minimize boilerplate while providing a robust routing system based on the file-system.
This chapter walks through the initialization of a modern SvelteKit application using the official sv CLI tool. We will explore the structure of the generated project, understand the purpose of svelte.config.js, and learn the directory conventions that drive SvelteKit’s file-system routing. By the end of this chapter, you will have a functional development environment ready for building dynamic web applications.
Key point: SvelteKit uses file-system-based routing within the src/routes/ directory; every folder becomes a URL path, and +page.svelte files define the UI, while +page.server.ts files provide the data layer for that route.
Why exists
The Routing Problem. Building a SPA router from scratch is complex. SvelteKit provides a file-system-based router that eliminates configuration files and ensures that your URLs match your directory structure.
The SSR & Hydration Problem. Single Page Apps (SPAs) often suffer from slow SEO and “blank screen” rendering. SvelteKit provides Server-Side Rendering by default, serving HTML that the browser can render immediately.
The Backend/Frontend Bridge. In traditional apps, you build a separate backend API. SvelteKit allows you to define server-side load functions (+page.server.ts) directly alongside your UI code, simplifying data fetching.
The Deployment Complexity. Deploying to different environments (Vercel, Netlify, Cloudflare, or static servers) used to require complex adapters. SvelteKit’s adapter system abstracts this, letting you deploy the same code anywhere.
The Development Workflow. Setup for modern web apps involves Webpack, Vite, TypeScript, and linting. The sv CLI provides a pre-configured, optimized environment that works out of the box with HMR (Hot Module Replacement).
a. Initializing with the sv CLI
The sv CLI is the standard tool for scaffolding Svelte and SvelteKit projects. It streamlines the selection of templates, TypeScript configuration, and dependency installation.
# Run the setup wizard
npx sv create my-app
During initialization, the CLI will prompt you to choose between a “Skeleton project,” “Library,” or “Documentation site.” For applications, choose the “Skeleton project.” You will also be asked to configure TypeScript and your preferred linter. Once initialized, navigate into the directory and install dependencies:
cd my-app
npm install
npm run dev -- --open
The npm run dev command starts the Vite development server, which provides lightning-fast HMR, allowing you to see changes instantly as you edit your files.
b. Understanding svelte.config.js
The svelte.config.js file is the central configuration hub for the Svelte compiler and SvelteKit. It controls how your code is processed, including preprocessors (like Tailwind CSS or Sass) and the target adapter.
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
export default {
preprocess: vitePreprocess(),
kit: {
adapter: adapter()
}
};
The preprocess property allows you to integrate tools that transform your CSS or script blocks before the Svelte compiler sees them. The kit object is where you define your adapter—which determines how the app is built for production—and other framework-specific settings like aliases or route protection.
c. Directory Conventions and Routing
SvelteKit relies heavily on a specific folder structure inside src/. The most important directory is src/routes/, where every sub-folder corresponds to a URL path.
src/routes/: The file-system router.src/lib/: Reusable components, utilities, and helper functions (accessible via the$libalias).src/app.html: The root HTML template for your entire application.static/: Static assets like images, fonts, andfavicon.icothat are served as-is.
Inside src/routes/, the naming convention is strict. A file named +page.svelte is the UI for that route, while +page.server.ts handles server-side logic and data fetching for that same route.
Complete Example Session
// ============================================
// PART 1: PROJECT SCAFFOLDING
// ============================================
// Run: npx sv create my-project
// Select: Skeleton project, TypeScript
// ============================================
// PART 2: THE CONFIGURATION (svelte.config.js)
// ============================================
import adapter from '@sveltejs/adapter-auto';
export default {
kit: { adapter: adapter() }
};
// ============================================
// PART 3: THE ROUTE STRUCTURE
// ============================================
// src/routes/+page.svelte (Home Page)
// src/routes/about/+page.svelte (About Page)
// ============================================
// PART 4: DATA LOADING (src/routes/+page.server.ts)
// ============================================
export function load() {
return { message: "Hello from the server!" };
}
This sequence illustrates the lifecycle of a new project, from scaffolding with the CLI to configuring the adapter and setting up the basic data-loading architecture.
Quick Reference
Route File Conventions
| Filename | Purpose |
|---|---|
+page.svelte | The UI/View for the route |
+page.server.ts | Data loading/Server-side logic |
+layout.svelte | Shared UI wrapper for nested routes |
+layout.server.ts | Shared data loader for nested routes |
+server.ts | API endpoints/HTTP handlers |
CLI Commands
| Command | Action |
|---|---|
npm run dev | Start development server |
npm run build | Build the project for production |
npm run preview | Preview the production build |
Best Practices
✅ Do This:
// Use $lib alias for imports
import { Button } from '$lib/components/Button.svelte'; // ✅
// Keep routes flat initially
src/routes/about/+page.svelte // ✅
// Use server files for secrets
// (API keys go in +page.server.ts, not .svelte) // ✅
// Name all route files with + prefix
// (e.g., +page.svelte) // ✅
❌ Don’t Do This:
// Use relative paths like ../../lib/
import { Button } from '../../lib/Button.svelte'; // ❌
// Deeply nest routes without layout needs
src/routes/a/b/c/d/e/+page.svelte // ❌
// Fetch client-side if server-side is available
// (Use +page.server.ts for SEO) // ❌
// Name files without the + prefix
// (e.g., index.svelte - will be ignored) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Route not found | Missing + prefix | Rename file to +page.svelte |
| Asset 404 | Wrong folder used | Put static files in /static |
| Import error | Wrong alias used | Use $lib for library files |
| Secrets leaked | API keys in .svelte | Move logic to +page.server.ts |
Real-World Examples
1. Home route
src/routes/+page.svelte
2. About route
src/routes/about/+page.svelte
3. Data loader
src/routes/user/+page.server.ts
4. Shared layout
src/routes/+layout.svelte
5. API endpoint
src/routes/api/data/+server.ts
6. Static asset
/static/favicon.png
7. Library import
import { user } from '$lib/stores/user';
8. Config preprocess
preprocess: vitePreprocess()
9. Adapter auto
import adapter from '@sveltejs/adapter-auto';
10. Preview build
npm run preview
Visual
SvelteKit File-System Routing
┌──────────────────────────────────────────────┐
│ src/routes/ │
│ ├── +page.svelte ( / ) │
│ ├── about/ │
│ │ └── +page.svelte ( /about ) │
│ └── user/ │
│ ├── +page.svelte ( /user ) │
│ └── +page.server.ts (Data Fetch) │
└──────────────────────────────────────────────┘
Request Flow
┌──────────────────────────────────────────────┐
│ BROWSER ──► HTTP REQUEST ──► SvelteKit │
│ │ │
│ +page.server.ts (Load Data) ◄───┘ │
│ │ │
│ +page.svelte (Render HTML) │
│ │ │
│ BROWSER ◄─── SSR RESPONSE │
└──────────────────────────────────────────────┘
Folder Structure
┌──────────────────────────────────────────────┐
│ /project │
│ ├── src/ │
│ │ ├── lib/ (Shared code) │
│ │ └── routes/ (App pages) │
│ ├── static/ (Public assets) │
│ ├── svelte.config.js (Configuration) │
│ └── vite.config.ts (Build tool) │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Initialization | npx sv create |
| Router | File-system based |
| UI File | +page.svelte |
| Server File | +page.server.ts |
| Library Alias | $lib |
| Config | svelte.config.js |
Key takeaways:
- Use the
svCLI. It is the official, optimized way to create projects and ensures your environment is configured for the latest SvelteKit standards. - Master the
+naming. Files starting with+are the backbone of the SvelteKit router. If your page isn’t showing, check for the+sign. - Embrace SSR. By default, SvelteKit renders on the server. Use
+page.server.tsto keep your secrets secure and your initial page load fast for SEO. - Use
$lib. The$libalias is your primary tool for code organization. Always use it to import your reusable components and utilities. - Understand the adapter.
svelte.config.jsis where you bridge your code to the host (Vercel, Node, etc.). Keep it clean and focused on your build targets.
Remember: SvelteKit is about standardizing the path from “idea” to “deployed application.” By sticking to the established directory conventions and embracing the + file system, you minimize configuration drift and focus entirely on building your features. Start with a skeleton, add your routes, and let the framework handle the rest.
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!