Planning full-stack app structure
I realize the user wants to build a full-stack SvelteKit application using PostgreSQL and Prisma ORM. They might need instructions and a repository structure, so it’s important to stay concise but thorough. I could break down the answer into several key sections like an overview, project setup, PostgreSQL and Prisma installation, schema definition, client setup, implementing CRUD routes, and testing. I should also add optional extras, but I'll avoid diving into authentication for now.Connecting to the database
I need to explain connecting to the database in both development and production environments to avoid the "PrismaClientInitializationError: too many connections." I plan to share a typical Prisma singleton example to manage connections properly. SvelteKit uses TypeScript by default, so I’ll craft the code accordingly, keeping explanations concise. I'll also touch on SvelteKit's server modules like +page.server.ts for server loads and actions and show simple examples. Finally, I’ll outline the project structure and mention the necessary npm installation commands.Installing and initializing Prisma
I plan to walk through the Prisma installation process, starting with these commands: npm install @prisma/client and npx prisma init. It’s important to note that prisma is provided as a dev dependency with npx prisma, so I should recommend using npm install -D prisma as well. Additionally, while building front-end forms, I might suggest using SvelteKit's form actions and focusing on progressive enhancement to ensure better user experience.Implementing server logic
I’m outlining the server-side code for SvelteKit with +page.server.ts. I’ll start by importing necessary types and functions from SvelteKit and Prisma. The load function fetches tasks from the database, ordering them by creation date. For actions, I’ll define a create function to handle task creation, checking for valid input. If the title is missing or invalid, it responds with an error. There's also a toggle function to update the task's completion status based on its ID, with error handling included.Crafting task management code
I'm finalizing the actions for managing tasks in SvelteKit's +page.server.ts with functions for creating, toggling, and deleting tasks. The corresponding +page.svelte includes a form for adding tasks and buttons for toggling or deleting them, using use:enhance for progressive enhancement. I’ll emphasize correct action paths, mentioning that named actions are formatted as ?/ACTION. While I could explore alternative RESTful routes, since the user wants a complete yet concise answer, I’ll focus on what's essential for their full-stack SvelteKit application. Below is a minimal but complete example of a full‑stack SvelteKit app using PostgreSQL with Prisma. It will be a simple Task list (CRUD).
1. Create the SvelteKit project
# Create project
npm create svelte@latest sveltekit-prisma-demo
cd sveltekit-prisma-demo
# Install dependencies
npm install
# (optional) enable TypeScript if you chose JS in the wizard
npm run check
# Run dev server to confirm it works
npm run dev -- --open
2. Install Prisma and PostgreSQL client
npm install @prisma/client
npm install -D prisma
Initialize Prisma:
npx prisma init
This creates:
prisma/schema.prisma
.env
3. Configure PostgreSQL & Prisma
3.1 PostgreSQL connection string
In .env, set your database URL (adjust user/pass/db/host/port):
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/sveltekit_prisma_demo?schema=public"
You can run Postgres via Docker, for example:
docker run --name sveltekit-postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=sveltekit_prisma_demo -p 5432:5432 -d postgres:16
3.2 Define the Prisma schema
Edit prisma/schema.prisma:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model Task {
id Int @id @default(autoincrement())
title String
done Boolean @default(false)
createdAt DateTime @default(now())
}
Run migration and generate client:
npx prisma migrate dev --name init
4. Create a Prisma client singleton for SvelteKit
Create src/lib/server/prisma.ts:
// src/lib/server/prisma.ts
import { PrismaClient } from '@prisma/client';
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: ['error', 'warn'],
});
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma;
}
This avoids multiple clients being created in dev (HMR).
5. Implement the backend (server load + form actions)
We’ll use SvelteKit’s server load and actions in the root route.
Create src/routes/+page.server.ts:
// src/routes/+page.server.ts
import type { Actions, PageServerLoad } from './$types';
import { fail } from '@sveltejs/kit';
import { prisma } from '$lib/server/prisma';
export const load: PageServerLoad = async () => {
const tasks = await prisma.task.findMany({
orderBy: { createdAt: 'desc' }
});
return { tasks };
};
export const actions: Actions = {
create: async ({ request }) => {
const data = await request.formData();
const title = data.get('title');
if (!title || typeof title !== 'string' || !title.trim()) {
return fail(400, { error: 'Title is required', title });
}
await prisma.task.create({
data: {
title: title.trim()
}
});
return { success: true };
},
toggle: async ({ request }) => {
const data = await request.formData();
const idRaw = data.get('id');
const id = Number(idRaw);
if (!id || Number.isNaN(id)) {
return fail(400, { error: 'Invalid task id' });
}
const task = await prisma.task.findUnique({ where: { id } });
if (!task) {
return fail(404, { error: 'Task not found' });
}
await prisma.task.update({
where: { id },
data: { done: !task.done }
});
return { success: true };
},
delete: async ({ request }) => {
const data = await request.formData();
const idRaw = data.get('id');
const id = Number(idRaw);
if (!id || Number.isNaN(id)) {
return fail(400, { error: 'Invalid task id' });
}
await prisma.task.delete({ where: { id } });
return { success: true };
}
};
This file is the backend: it reads/writes to PostgreSQL via Prisma and exposes data/actions to the page.
6. Implement the frontend page
Create src/routes/+page.svelte:
<script lang="ts">
import type { PageData } from './$types';
import { enhance } from '$app/forms';
export let data: PageData;
</script>
<svelte:head>
<title>Tasks | SvelteKit + Prisma</title>
</svelte:head>
<main>
<h1>Task List</h1>
<!-- Create Task -->
<form method="post" action="?/create" use:enhance>
<input
name="title"
placeholder="New task"
required
autocomplete="off"
/>
<button type="submit">Add</button>
</form>
{#if data.tasks.length === 0}
<p>No tasks yet. Add one!</p>
{:else}
<ul>
{#each data.tasks as task}
<li>
<form method="post" action="?/toggle" use:enhance style="display:inline">
<input type="hidden" name="id" value={task.id} />
<button type="submit">
{task.done ? '✅' : '⬜'}
</button>
</form>
<span style:text-decoration={task.done ? 'line-through' : 'none'}>
{task.title}
</span>
<form method="post" action="?/delete" use:enhance style="display:inline">
<input type="hidden" name="id" value={task.id} />
<button type="submit">🗑</button>
</form>
</li>
{/each}
</ul>
{/if}
</main>
<style>
main {
max-width: 40rem;
margin: 2rem auto;
padding: 0 1rem;
font-family: system-ui, sans-serif;
}
form {
margin: 0.5rem 0;
}
input[name='title'] {
padding: 0.3rem 0.5rem;
margin-right: 0.5rem;
}
button {
cursor: pointer;
}
ul {
list-style: none;
padding-left: 0;
}
li {
margin: 0.25rem 0;
}
</style>
Notes:
load data (tasks) from the server is available as data.tasks.
- Forms use named actions (
create, toggle, delete) via action="?/actionName".
use:enhance progressively enhances forms with fetch (no full page reload), but also works without JS.
7. Run the app
Make sure Postgres is running and accessible at the DATABASE_URL.
Then:
npm run dev
Open http://localhost:5173 (or whichever port SvelteKit shows).
You should be able to:
- Add tasks
- Toggle tasks as done/undone
- Delete tasks
All of this is persisted in PostgreSQL via Prisma.
8. Optional next steps
- Add input validation (e.g., zod) before writing to the DB.
- Add authentication (e.g., Lucia, Auth.js) and relate
Task to a User model.
- Add
prisma/seed.ts for seed data and run with npx prisma db seed.
- Deploy using a Node adapter (e.g., adapter-node) or a platform’s adapter and configure a managed Postgres instance.
If you tell me your deployment target (Vercel, Fly.io, etc.), I can show a specific config for running this stack in production.