🌐 Web Development

SvelteKit

SvelteKit

A Svelte-based full-stack framework. Supports SSR, SSG, and API routes.

πŸ“– Detailed Explanation

SvelteKit (pronounced "Svelte-kit") is a full-stack web application framework based on Svelte. Just as Next.js does for React and Nuxt does for Vue, SvelteKit provides the features needed for production web apps on top of Svelte, such as routing, server-side rendering (SSR), static site generation (SSG), and API endpoints. Version 1.0 was released in December 2022, and it is developed officially by the Svelte team.

The key feature of SvelteKit is file-based routing. The src/routes directory structure becomes the URL path. +page.svelte is the page component, and +page.server.ts handles data loading (the load function) and form handling (actions) that run only on the server. You can create REST API endpoints with +server.ts, so you can build a full-stack app without a separate backend.

Rendering strategies can be configured flexibly on a per-page basis. SSR (server-side rendering) is used by default, but if you set export const prerender = true in +page.ts, static HTML is generated at build time (SSG). You can also use only client-side rendering with export const ssr = false, or create pure HTML pages without a JavaScript bundle with export const csr = false.

SvelteKit can be deployed to a variety of platforms through its Adapter system. There are official and community adapters such as adapter-vercel, adapter-cloudflare, adapter-netlify, and adapter-node, enabling flexible deployment from serverless edge to traditional Node.js servers. Combined with Svelte's compiler-based optimizations, it achieves very small bundle sizes and fast initial loading.

πŸ’» Code Example

Project structure

my-sveltekit-app/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”œβ”€β”€ +page.svelte           # / (ν™ˆνŽ˜μ΄μ§€)
β”‚   β”‚   β”œβ”€β”€ +page.server.ts        # μ„œλ²„ 둜직
β”‚   β”‚   β”œβ”€β”€ +layout.svelte         # 곡톡 λ ˆμ΄μ•„μ›ƒ
β”‚   β”‚   β”œβ”€β”€ about/
β”‚   β”‚   β”‚   └── +page.svelte       # /about
β”‚   β”‚   β”œβ”€β”€ blog/
β”‚   β”‚   β”‚   β”œβ”€β”€ +page.svelte       # /blog (λͺ©λ‘)
β”‚   β”‚   β”‚   β”œβ”€β”€ +page.server.ts
β”‚   β”‚   β”‚   └── [slug]/
β”‚   β”‚   β”‚       β”œβ”€β”€ +page.svelte   # /blog/:slug (상세)
β”‚   β”‚   β”‚       └── +page.server.ts
β”‚   β”‚   └── api/
β”‚   β”‚       └── posts/
β”‚   β”‚           └── +server.ts     # /api/posts (API)
β”‚   β”œβ”€β”€ lib/
β”‚   β”‚   β”œβ”€β”€ components/            # μž¬μ‚¬μš© μ»΄ν¬λ„ŒνŠΈ
β”‚   β”‚   └── server/                # μ„œλ²„ μ „μš© μ½”λ“œ
β”‚   β”œβ”€β”€ app.html                   # HTML ν…œν”Œλ¦Ώ
β”‚   └── app.d.ts                   # νƒ€μž… μ •μ˜
β”œβ”€β”€ static/                        # 정적 파일
β”œβ”€β”€ svelte.config.js
β”œβ”€β”€ vite.config.ts
└── package.json

Page Components and Data Loading

<!-- src/routes/blog/[slug]/+page.svelte -->
<script lang="ts">
  import type { PageData } from './$types';

  export let data: PageData;

  // dataλŠ” +page.server.ts의 load ν•¨μˆ˜μ—μ„œ λ°˜ν™˜
</script>

<svelte:head>
  <title>{data.post.title} | My Blog</title>
  <meta name="description" content={data.post.excerpt} />
</svelte:head>

<article>
  <h1>{data.post.title}</h1>
  <p class="meta">
    {new Date(data.post.createdAt).toLocaleDateString('ko-KR')}
    Β· {data.post.author.name}
  </p>
  <div class="content">
    {@html data.post.content}
  </div>
</article>

<style>
  article {
    max-width: 800px;
    margin: 0 auto;
    padding: 2rem;
  }
  .meta {
    color: #666;
    margin-bottom: 2rem;
  }
</style>

Server-Side Data Loading

// src/routes/blog/[slug]/+page.server.ts
import { error } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { db } from '$lib/server/database';

export const load: PageServerLoad = async ({ params, locals }) => {
  const post = await db.post.findUnique({
    where: { slug: params.slug },
    include: { author: true }
  });

  if (!post) {
    throw error(404, {
      message: '포슀트λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.'
    });
  }

  // 쑰회수 증가 (비동기, 응닡 λŒ€κΈ° μ•ˆ 함)
  db.post.update({
    where: { id: post.id },
    data: { views: { increment: 1 } }
  });

  return {
    post,
    user: locals.user  // hooks.server.tsμ—μ„œ μ„€μ •
  };
};

// 정적 생성 μ˜΅μ…˜
export const prerender = false;  // 동적 νŽ˜μ΄μ§€

Form Actions (Server-Side Form Handling)

// src/routes/contact/+page.server.ts
import { fail, redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
import { sendEmail } from '$lib/server/email';

export const actions: Actions = {
  default: async ({ request, cookies }) => {
    const formData = await request.formData();
    const name = formData.get('name')?.toString();
    const email = formData.get('email')?.toString();
    const message = formData.get('message')?.toString();

    // μœ νš¨μ„± 검사
    const errors: Record<string, string> = {};
    if (!name || name.length < 2) {
      errors.name = '이름은 2자 이상이어야 ν•©λ‹ˆλ‹€.';
    }
    if (!email || !email.includes('@')) {
      errors.email = 'μ˜¬λ°”λ₯Έ 이메일을 μž…λ ₯ν•˜μ„Έμš”.';
    }
    if (!message || message.length < 10) {
      errors.message = 'λ©”μ‹œμ§€λŠ” 10자 이상이어야 ν•©λ‹ˆλ‹€.';
    }

    if (Object.keys(errors).length > 0) {
      return fail(400, { errors, name, email, message });
    }

    try {
      await sendEmail({
        to: 'contact@example.com',
        subject: `[문의] ${name}λ‹˜μ˜ λ©”μ‹œμ§€`,
        body: `이름: ${name}\n이메일: ${email}\n\n${message}`
      });

      // 성곡 μ‹œ 감사 νŽ˜μ΄μ§€λ‘œ λ¦¬λ‹€μ΄λ ‰νŠΈ
      throw redirect(303, '/contact/thanks');
    } catch (e) {
      if (e instanceof Response) throw e;  // redirectλŠ” throw
      return fail(500, { error: '전솑에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€.' });
    }
  }
};
<!-- src/routes/contact/+page.svelte -->
<script lang="ts">
  import { enhance } from '$app/forms';
  import type { ActionData } from './$types';

  export let form: ActionData;
</script>

<h1>λ¬Έμ˜ν•˜κΈ°</h1>

<form method="POST" use:enhance>
  <div class="field">
    <label for="name">이름</label>
    <input
      type="text"
      id="name"
      name="name"
      value={form?.name ?? ''}
    />
    {#if form?.errors?.name}
      <p class="error">{form.errors.name}</p>
    {/if}
  </div>

  <div class="field">
    <label for="email">이메일</label>
    <input
      type="email"
      id="email"
      name="email"
      value={form?.email ?? ''}
    />
    {#if form?.errors?.email}
      <p class="error">{form.errors.email}</p>
    {/if}
  </div>

  <div class="field">
    <label for="message">λ©”μ‹œμ§€</label>
    <textarea
      id="message"
      name="message"
      rows="5"
    >{form?.message ?? ''}</textarea>
    {#if form?.errors?.message}
      <p class="error">{form.errors.message}</p>
    {/if}
  </div>

  <button type="submit">전솑</button>

  {#if form?.error}
    <p class="error">{form.error}</p>
  {/if}
</form>

API Endpoints

// src/routes/api/posts/+server.ts
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { db } from '$lib/server/database';

// GET /api/posts
export const GET: RequestHandler = async ({ url }) => {
  const page = parseInt(url.searchParams.get('page') ?? '1');
  const limit = parseInt(url.searchParams.get('limit') ?? '10');

  const posts = await db.post.findMany({
    skip: (page - 1) * limit,
    take: limit,
    orderBy: { createdAt: 'desc' },
    select: {
      id: true,
      slug: true,
      title: true,
      excerpt: true,
      createdAt: true
    }
  });

  const total = await db.post.count();

  return json({
    posts,
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit)
    }
  });
};

// POST /api/posts
export const POST: RequestHandler = async ({ request, locals }) => {
  if (!locals.user) {
    throw error(401, '둜그인이 ν•„μš”ν•©λ‹ˆλ‹€.');
  }

  const body = await request.json();

  const post = await db.post.create({
    data: {
      title: body.title,
      slug: body.slug,
      content: body.content,
      authorId: locals.user.id
    }
  });

  return json(post, { status: 201 });
};

svelte.config.js Configuration

// svelte.config.js
import adapter from '@sveltejs/adapter-vercel';  // λ˜λŠ” adapter-node
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';

/** @type {import('@sveltejs/kit').Config} */
const config = {
  preprocess: vitePreprocess(),

  kit: {
    adapter: adapter({
      runtime: 'edge',  // Vercel Edge Functions
      regions: ['icn1']  // μ„œμšΈ 리전
    }),

    alias: {
      $components: 'src/lib/components',
      $utils: 'src/lib/utils'
    },

    // CSP μ„€μ •
    csp: {
      mode: 'auto',
      directives: {
        'script-src': ['self']
      }
    },

    // ν™˜κ²½ λ³€μˆ˜ 접두사 (κΈ°λ³Έ: PUBLIC_)
    env: {
      publicPrefix: 'PUBLIC_'
    }
  }
};

export default config;

πŸ—£οΈ How It's Said in Practice

  • "If you build with SvelteKit, the bundle size is less than half of React's, so mobile performance is definitely better."
  • "If you fetch data with the load function in +page.server.ts, SSR happens automatically, so there's no need to worry about SEO."
  • "If you handle forms with actions, they work even without JavaScript and get progressive enhancement, so accessibility is good too."
  • "If you deploy to Vercel Edge, it responds quickly in the Seoul region with no Cold Start. Just use adapter-vercel."
  • "Can you explain the environment (server/client) in which SvelteKit's load function runs, and what is the difference between +page.ts and +page.server.ts?"
  • "How do you configure SvelteKit's rendering strategies (SSR, SSG, CSR), and when do you use each?"
  • "What is SvelteKit's adapter system, and why is it useful?"
  • "What are the roles of form actions and use:enhance?"

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

  • "This data must not be exposed to the client. Move it from +page.ts to +page.server.ts."
  • "If you add use:enhance to a form, it submits without a page refresh and handling loading states becomes easier."
  • "This page is static, so adding export const prerender = true and generating it at build time will improve performance."

⚠️ Cautions

Distinguishing Server/Client Code

Code in +page.server.ts runs only on the server, while +page.ts can run on both the server and the client. Always write sensitive code such as DB connections and API keys in +page.server.ts or inside $lib/server/.

Ecosystem Size

The Svelte/SvelteKit ecosystem is smaller than that of React/Next.js. Third-party library choices may be limited, and this is something to consider in terms of community support and the hiring market.

Hydration Mismatch

A warning is raised if the SSR-rendered HTML and the client Hydration result differ. Use browser-only APIs (window, localStorage) inside onMount or after a browser check.

πŸ”— Related Terms

πŸ“š Learn More