Svelte 52 ๐งก Directory Conventions, App Configuration, and Routing Tree
SvelteKit provides a rigid, opinionated directory structure designed to minimize configuration overhead while maximizing productivity. By standardizing where files live, the framework enables automatic routing, asset serving, and build-time optimization. At the heart of this structure is the project root, which coordinates with configuration files to bridge the gap between source code and the final production bundle.
This chapter covers the essential architectural building blocks of a SvelteKit application. We will examine the purpose of each top-level directory, the role of svelte.config.js in controlling the build process, and the intricate mechanics of the src/routes tree. By mastering these conventions, you move from “guessing where files go” to leveraging SvelteKitโs built-in automation to maintain a scalable, maintainable codebase.
Key point: SvelteKit architecture is rooted in the “Convention over Configuration” philosophy, where your directory structure defines the routing tree, while svelte.config.js and vite.config.ts manage the engineโpreprocessors, deployment adapters, and module resolution.
Why exists
The Fragmented Config Problem. Historically, web frameworks required complex, custom configurations for every plugin and build tool. SvelteKit exists to centralize these settings into svelte.config.js, ensuring all build-time tools like TypeScript preprocessors and adapters share a single source of truth.
The Routing Complexity Problem. Defining routes in a central file leads to bloated navigation tables that grow impossible to manage as an application expands. The src/routes tree exists to eliminate this by making your file system the routing map, making it trivial to locate the logic for any specific URL.
The Asset Path Problem. Developers frequently struggle with serving static files versus assets that need build-time processing. The static/ directory exists to provide a simple, predictable location for files that should remain untouched by the bundler, such as favicon.ico or robots.txt.
The Source Code Noise Problem. Without a src/ convention, project roots quickly become cluttered with build scripts, CSS, and configuration files. This separation exists to ensure that your actual application logic is isolated, clean, and easily identifiable for developers and build tools alike.
The Environment Mismatch Problem. Moving code from development to production often breaks paths or environment variables. SvelteKitโs structure exists to facilitate automated adapter-based deployment, where the same src/ structure works identically across local dev, Node.js servers, or static edge platforms.
a. Project Structure Overview
A standard SvelteKit project consists of several core directories. The src/ folder is the primary workspace. Within it, routes/ handles the page-based routing, lib/ serves as the centralized place for shared utilities, and app.html acts as the root template for every page.
// project-root/
// โโโ src/
// โ โโโ lib/ // Shared code, components, utility functions
// โ โโโ routes/ // The file-system routing tree
// โ โโโ app.html // The root HTML template
// โโโ static/ // Public assets (served as-is)
// โโโ svelte.config.js // Svelte/SvelteKit configuration
// โโโ vite.config.ts // Vite build configuration
The src/lib folder is particularly important because SvelteKit maps the $lib alias to this location. This allows you to import shared components like import Button from '$lib/components/Button.svelte' without deep relative pathing like ../../...
b. The svelte.config.js File
The svelte.config.js file is the central nervous system for your Svelte compiler settings. While vite.config.ts manages the development server and bundling, svelte.config.js manages how Svelte components are parsed and which adapters are used for deployment.
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
export default {
preprocess: vitePreprocess(), // Enables TS, SCSS, and PostCSS
kit: {
adapter: adapter(), // Deployment adapter (e.g., node, vercel, netlify)
alias: {
'$components': 'src/components' // Custom aliases
}
}
};
This configuration ensures that every Svelte component is processed consistently. By setting the adapter, you dictate how the project will be built for production. If you change your deployment platform (e.g., from Vercel to a local Node.js server), you simply swap the adapter here, and the framework handles the rest.
c. The Routing Tree in src/routes
The src/routes folder uses a specific file naming convention to define functionality. Files beginning with + are special: +page.svelte defines the UI, +page.server.ts handles server-side data fetching, +layout.svelte provides shared templates, and +error.svelte handles specific error states.
// Route: /blog/[slug]
// 1. src/routes/blog/[slug]/+page.svelte // The View
// 2. src/routes/blog/[slug]/+page.server.ts // Data Loading
// 3. src/routes/blog/[slug]/+layout.svelte // Nested Layout
You can also use “route groups” to organize routes without changing the URL path. By naming a directory (group-name), the parentheses are ignored in the actual URL. This allows you to separate, for example, (auth) routes from (app) routes while keeping them logically grouped in the project tree.
Complete Example Session
// ============================================
// PART 1: SVELTE.CONFIG.JS
// ============================================
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
export default {
preprocess: vitePreprocess(),
kit: { adapter: adapter() }
};
// ============================================
// PART 2: THE ROOT TEMPLATE
// ============================================
// src/app.html: Use %sveltekit.head% and %sveltekit.body%
// These are placeholders for the router.
// ============================================
// PART 3: SHARED LIB
// ============================================
// src/lib/server/db.ts: Import via $lib/server/db
export const db = { users: [] };
// ============================================
// PART 4: ROUTE GROUPING
// ============================================
// src/routes/(auth)/login/+page.svelte
// URL: /login (not /auth/login)
// ============================================
// PART 5: DYNAMIC PARAMS
// ============================================
// src/routes/user/[id]/+page.server.ts
export const load = ({ params }) => ({ id: params.id });
// ============================================
// PART 6: LAYOUTS
// ============================================
// src/routes/+layout.svelte: Wraps all pages.
// ============================================
// PART 7: ERROR HANDLING
// ============================================
// src/routes/+error.svelte: Catches all errors.
// ============================================
// PART 8: SERVER ENDPOINTS
// ============================================
// src/routes/api/data/+server.ts
export const GET = () => new Response("data");
// ============================================
// PART 9: THE ALIAS
// ============================================
// import { x } from '$lib/x';
// ============================================
// PART 10: STATIC ASSETS
// ============================================
// static/logo.png -> available at /logo.png
These parts show the standard structural components required to build and configure a functional SvelteKit application.
Quick Reference
Special File Types
| Filename | Purpose |
|---|---|
+page.svelte | Page content |
+page.server.ts | Server-only data |
+layout.svelte | Shared layout |
+error.svelte | Error handler |
+server.ts | API endpoint |
Configuration
| Config File | Purpose |
|---|---|
svelte.config.js | Svelte compiler + Kit |
vite.config.ts | Vite/Server config |
tsconfig.json | TS compiler config |
Directory Aliases
| Alias | Path |
|---|---|
$lib | src/lib |
$env | Dynamic/Static env |
Best Practices
โ Do This:
// Keep shared code in $lib
import { nav } from '$lib/nav'; // โ
// Use groups for organizational logic
src/routes/(marketing)/home/+page.svelte // โ
// Use relative import for tests
import { sum } from './math'; // โ
// Clean up static folder
// Keep only public-facing assets like favicons // โ
โ Don’t Do This:
// Don't put routes in src/components
// That will break routing // โ
// Don't import from outside $lib without aliases
import { x } from '../../../../lib/x'; // โ
// Don't edit app.html for JS injection
// Use hooks.server.ts for that // โ
// Don't name folders +page (must be +page.svelte) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Route not found | Missing +page.svelte | Add file to directory |
| Asset 404 | Wrong folder | Move to static/ |
| Config ignored | Wrong filename | Check svelte.config.js |
| Alias fail | Missing jsconfig.json | Run npm run sync |
Real-World Examples
1. Define custom alias
// svelte.config.js
alias: { '$utils': 'src/utils' }
2. Grouped route
// src/routes/(app)/dashboard/+page.svelte
3. Dynamic route
// src/routes/products/[id]/+page.svelte
4. Shared library
// src/lib/types.ts
export type User = { name: string };
5. API route
// src/routes/api/ping/+server.ts
export const GET = () => new Response('pong');
6. Layout usage
// src/routes/+layout.svelte
<slot />
7. Error handling
// src/routes/+error.svelte
<p>Something went wrong</p>
8. Static file
// static/robots.txt
9. Server data
// src/routes/+page.server.ts
export const load = () => ({ ok: true });
10. Preprocessor config
// svelte.config.js
preprocess: vitePreprocess()
Visual
The Routing Hierarchy
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ src/routes/ โ
โ โโโ +layout.svelte (Root) โ
โ โโโ (auth)/ โ
โ โ โโโ login/ โ
โ โ โโโ +page.svelte โ
โ โโโ app/ โ
โ โโโ dashboard/ โ
โ โโโ +page.svelte โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Configuration Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ svelte.config.js โ
โ โโโ adapter (Target platform) โ
โ โโโ preprocess (Typescript/CSS) โ
โ โโโ kit settings (Aliases) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
File Structure
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Root Folder โ
โ โโโ src/ (Source logic) โ
โ โโโ static/ (Public assets) โ
โ โโโ svelte.config.js (Kit Config) โ
โ โโโ vite.config.ts (Build Config) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Root Dir | src/ |
| Route Folder | src/routes/ |
| Shared Library | src/lib/ |
| Public Assets | static/ |
| Config File | svelte.config.js |
| Alias | $lib |
| Special Files | + prefixed |
Key takeaways:
- Folders define routes. Every directory in
src/routestranslates to a URL path unless it is a route group(folder). svelte.config.jsis the configuration authority. Use it to manage adapters, preprocessors, and compiler aliases.src/libis the official shared bucket. Always use the$libalias for importing code between different parts of your application.- Static assets stay in
static/. These files are served directly by the web server and are not processed by the Vite bundler. - Special files control behavior. Use
+page,+layout, and+errorto handle rendering, data, and edge cases respectively.
Remember: SvelteKit enforces a clear boundary between your logic (src/) and your assets (static/), while mapping the physical file structure directly to your application’s logical routes. Mastering this hierarchy reduces the need for custom routing configuration and ensures that your application remains modular, portable, and easy to navigate for other developers.
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!