bash
# Step 1: Create a new SvelteKit project
npm create svelte@latest todo-app
cd todo-app
# Step 2: Select options during setup
# - Skeleton project: Yes
# - TypeScript: Yes (recommended for Prisma)
# - ESLint: Yes
# - Prettier: Yes
# - Playwright: No
# - Vitest: No
# - npm: Yes
# Step 3: Install dependencies
npm install
# Step 4: Install Prisma, TailwindCSS (for styling), and other deps
npm install prisma @prisma/client
npm install -D @tailwindcss/vite tailwindcss postcss autoprefixer
npm install @sveltejs/adapter-node # For Node.js server deployment
# Step 5: Initialize TailwindCSS
npx tailwindcss init -p
# Step 6: Initialize Prisma
npx prisma init
# Step 7: Set up PostgreSQL
# Option A: Local Postgres (create DB named 'todoapp')
# Option B: Docker (recommended for quick setup)
cat > docker-compose.yml << 'EOF'
version: '3.8'
services:
postgres:
image: postgres:16
restart: always
environment:
POSTGRES_DB: todoapp
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
ports:
- '5432:5432'
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
EOF
# Start Postgres with Docker
docker-compose up -d
EOF
# Step 8: Configure .env (update DATABASE_URL with your setup)
cat > .env << 'EOF'
DATABASE_URL="postgresql://postgres:password@localhost:5432/todoapp?schema=public"
EOF
# Step 9: Update Prisma schema (prisma/schema.prisma)
cat > prisma/schema.prisma << 'EOF'
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Todo {
id Int @id @default(autoincrement())
title String
completed Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
EOF
# Step 10: Run Prisma migrations and generate client
npx prisma migrate dev --name init
npx prisma generate
# Step 11: Update package.json scripts (add these)
# Edit package.json:
# "dev": "vite dev",
# "build": "vite build",
# "preview": "vite preview",
# Add:
# "db:push": "prisma db push",
# "db:migrate": "prisma migrate dev",
# "db:studio": "prisma studio"
# Step 12: Configure svelte.config.js
cat > svelte.config.js << 'EOF'
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/kit/vite';
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter()
}
};
export default config;
EOF
# Step 13: Configure TailwindCSS (tailwind.config.js)
cat > tailwind.config.js << 'EOF'
/** @type {import('tailwindcss').Config} */
export default {
content: ['./src/**/*.{html,js,svelte,ts}'],
theme: {
extend: {}
},
plugins: [],
darkMode: 'class'
};
EOF
# Step 14: Update src/app.html
cat > src/app.html << 'EOF'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover" class="bg-gray-100 dark:bg-gray-900">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
EOF
# Step 15: Create src/app.css (global styles + Tailwind)
cat > src/app.css << 'EOF'
@tailwind base;
@tailwind components;
@tailwind utilities;
EOF
# Step 16: Update src/routes/+layout.svelte (with Tailwind)
cat > src/routes/+layout.svelte << 'EOF'
<script lang="ts">
import '../app.css';
</script>
<svelte:head>
<title>Todo App</title>
</svelte:head>
<div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
<slot />
</div>
EOF
# Step 17: Update src/routes/+layout.ts (server-side layout for Prisma)
cat > src/routes/+layout.server.ts << 'EOF'
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async () => {
return {};
};
EOF
# Step 18: Create Prisma client (src/lib/db.ts)
mkdir -p src/lib
cat > src/lib/db.ts << 'EOF'
import { PrismaClient } from '@prisma/client';
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const prisma = globalForPrisma.prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
EOF
# Step 19: Create API routes
# GET/POST all todos: src/routes/api/todos/+server.ts
cat > src/routes/api/todos/+server.ts << 'EOF'
import { json } from '@sveltejs/kit';
import { prisma } from '$lib/db';
import type { Todo } from '@prisma/client';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async () => {
const todos: Todo[] = await prisma.todo.findMany({
orderBy: { createdAt: 'desc' }
});
return json(todos);
};
export const POST: RequestHandler = async ({ request }) => {
const { title } = await request.json();
const todo = await prisma.todo.create({
data: { title }
});
return json(todo, { status: 201 });
};
EOF
# GET/PUT/DELETE single todo: src/routes/api/todos/[id]/+server.ts
mkdir -p src/routes/api/todos/[id]
cat > src/routes/api/todos/[id]/+server.ts << 'EOF'
import { json, error } from '@sveltejs/kit';
import { prisma } from '$lib/db';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ params }) => {
const todo = await prisma.todo.findUnique({
where: { id: parseInt(params.id) }
});
if (!todo) throw error(404, 'Todo not found');
return json(todo);
};
export const PUT: RequestHandler = async ({ params, request }) => {
const { title, completed } = await request.json();
const todo = await prisma.todo.update({
where: { id: parseInt(params.id) },
data: { title, completed }
});
return json(todo);
};
export const DELETE: RequestHandler = async ({ params }) => {
await prisma.todo.delete({
where: { id: parseInt(params.id) }
});
return new Response(null, { status: 204 });
};
EOF
# Step 20: Create frontend page: src/routes/+page.svelte
cat > src/routes/+page.svelte << 'EOF'
<script lang="ts">
import { onMount } from 'svelte';
import type { Todo } from '@prisma/client';
let todos: Todo[] = [];
let newTitle = '';
let loading = true;
const loadTodos = async () => {
const res = await fetch('/api/todos');
todos = await res.json();
loading = false;
};
const addTodo = async () => {
if (!newTitle.trim()) return;
const res = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: newTitle })
});
if (res.ok) {
newTitle = '';
await loadTodos();
}
};
const toggleTodo = async (id: number, completed: boolean) => {
await fetch(`/api/todos/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ completed: !completed })
});
await loadTodos();
};
const deleteTodo = async (id: number) => {
await fetch(`/api/todos/${id}`, { method: 'DELETE' });
await loadTodos();
};
const updateTitle = async (id: number, title: string) => {
await fetch(`/api/todos/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title })
});
await loadTodos();
};
onMount(loadTodos);
</script>
<div class="max-w-md mx-auto bg-white dark:bg-gray-800 rounded-xl shadow-md overflow-hidden md:max-w-2xl">
<div class="p-8">
<h1 class="text-3xl font-bold text-gray-900 dark:text-white mb-6 text-center">Todo App</h1>
<div class="flex mb-6">
<input
bind:value={newTitle}
on:keydown={(e) => e.key === 'Enter' && addTodo()}
placeholder="Add a new todo..."
class="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white"
/>
<button
on:click={addTodo}
class="ml-2 px-6 py-2 bg-blue-500 text-white font-medium rounded-lg hover:bg-blue-600 focus:ring-2 focus:ring-blue-500"
>
Add
</button>
</div>
{#if loading}
<p class="text-center text-gray-500 dark:text-gray-400">Loading...</p>
{:else if todos.length === 0}
<p class="text-center text-gray-500 dark:text-gray-400">No todos yet. Add one!</p>
{:else}
<ul class="space-y-3">
{#each todos as todo}
<li class="flex items-center p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
<input
type="checkbox"
class="w-5 h-5 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
checked={todo.completed}
on:change={() => toggleTodo(todo.id, todo.completed)}
/>
<input
bind:value={todo.title}
on:blur={(e) => updateTitle(todo.id, e.currentTarget.value)}
class="ml-3 flex-1 px-3 py-2 text-gray-900 dark:text-white bg-transparent border-none focus:outline-none {todo.completed ? 'line-through text-gray-500' : ''}"
class:font-medium={!todo.completed}
/>
<button
on:click={() => deleteTodo(todo.id)}
class="ml-4 text-red-500 hover:text-red-700"
>
✕
</button>
</li>
{/each}
</ul>
{/if}
</div>
</div>
EOF
# Step 21: Run the app
# Start Postgres (if using Docker): docker-compose up -d
# Dev server: npm run dev
# Open http://localhost:5173
# Prisma Studio: npx prisma studio (http://localhost:5555)
# Build for production: npm run build
# Preview: npm run preview
# Deployment notes:
# - Use Vercel (SvelteKit adapter-auto), Railway/Neon for Postgres, or self-host with adapter-node.
# - Set DATABASE_URL in env vars.
# - Run migrations on deploy: npx prisma migrate deploy