SvelteKit
SvelteKit
A Svelte-based full-stack framework. Supports SSR, SSG, and API routes.
SvelteKit
A Svelte-based full-stack framework. Supports SSR, SSG, and API routes.
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.
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
<!-- 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>
// 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; // λμ νμ΄μ§
// 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>
// 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
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;
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
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/.
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.
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.