| | |

Svelte 52 ๐Ÿงก Directory Conventions, App Configuration, and Routing Tree

โฑ๏ธ Estimated read: 8 min | |

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

FilenamePurpose
+page.sveltePage content
+page.server.tsServer-only data
+layout.svelteShared layout
+error.svelteError handler
+server.tsAPI endpoint

Configuration

Config FilePurpose
svelte.config.jsSvelte compiler + Kit
vite.config.tsVite/Server config
tsconfig.jsonTS compiler config

Directory Aliases

AliasPath
$libsrc/lib
$envDynamic/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

PitfallWhy It HappensFix
Route not foundMissing +page.svelteAdd file to directory
Asset 404Wrong folderMove to static/
Config ignoredWrong filenameCheck svelte.config.js
Alias failMissing jsconfig.jsonRun 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

ItemValue
Root Dirsrc/
Route Foldersrc/routes/
Shared Librarysrc/lib/
Public Assetsstatic/
Config Filesvelte.config.js
Alias$lib
Special Files+ prefixed

Key takeaways:

  • Folders define routes. Every directory in src/routes translates to a URL path unless it is a route group (folder).
  • svelte.config.js is the configuration authority. Use it to manage adapters, preprocessors, and compiler aliases.
  • src/lib is the official shared bucket. Always use the $lib alias 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 +error to 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.

Was this helpful?


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!