SvelteKit & Prisma Full-Stack CRUD Application
Table of Contents
Introduction
In this tutorial, you will learn how to build a full-stack CRUD application using SvelteKit and Prisma. This guide will walk you through the process of setting up your environment, configuring your database, and implementing create, read, update, and delete functionalities. SvelteKit is a powerful framework for modern web applications, and Prisma simplifies database interactions.
Step 1: Set Up Your Environment
-
Install Necessary Packages
- Open your terminal and navigate to your project directory.
- Run the following command to install Prisma and the Prisma Client:
npm install prisma @prisma/client
-
Initialize Prisma
- After installing, initialize Prisma with:
npx prisma init
- This command creates a
prisma
folder with aschema.prisma
file.
- After installing, initialize Prisma with:
-
Configure Database
- Open
schema.prisma
and set the provider to SQLite:datasource db { provider = "sqlite" url = "file:./dev.sqlite" }
- Open
Step 2: Define Your Data Model
-
Create a Model
- In
schema.prisma
, define your data model for articles:model Article { id Int @id @default(autoincrement()) title String content String }
- In
-
Push the Database Changes
- Open your terminal and run:
npx prisma db push
- This command creates the SQLite database and the
Article
table.
- Open your terminal and run:
Step 3: Set Up Prisma Client
- Create Prisma Client File
- Create a new directory called
lib/server
, and within it, create a file namedprisma.ts
. - Add the following code to handle Prisma Client:
import { PrismaClient } from '@prisma/client'; const globalPrisma = global as any; export const prisma = globalPrisma.prisma || new PrismaClient(); if (process.env.NODE_ENV !== 'production') { globalPrisma.prisma = prisma; }
- Create a new directory called
Step 4: Implement Create Functionality
-
Create Action for Adding Articles
- Create a new file named
+page.server.ts
in your routes folder. - Add the following code for creating articles:
import { prisma } from '../lib/server/prisma'; export const actions = { createArticle: async ({ request }) => { const formData = await request.formData(); const title = formData.get('title') as string; const content = formData.get('content') as string; try { await prisma.article.create({ data: { title, content } }); return { status: 201 }; } catch (error) { console.error(error); return { status: 500 }; } } };
- Create a new file named
-
Update Your Form
- Ensure your form calls the
createArticle
action by setting its method to POST.
- Ensure your form calls the
Step 5: Implement Read Functionality
-
Load Articles from Database
- In the same
+page.server.ts
file, add a load function:export const load = async () => { const articles = await prisma.article.findMany(); return { articles }; };
- In the same
-
Display Articles
- In your component, loop through the articles data and display it:
{#each articles as article} <h2>{article.title}</h2> <p>{article.content}</p> {/each}
- In your component, loop through the articles data and display it:
Step 6: Implement Delete Functionality
-
Create Delete Action
- Add a new delete action in your
+page.server.ts
file:export const actions = { deleteArticle: async ({ request }) => { const url = new URL(request.url); const id = url.searchParams.get('id'); if (!id) return { status: 400 }; try { await prisma.article.delete({ where: { id: Number(id) } }); return { status: 200 }; } catch (error) { console.error(error); return { status: 500 }; } } };
- Add a new delete action in your
-
Link Delete Button to Action
- Wrap your delete button in a form with the delete action.
Step 7: Implement Update Functionality
-
Create Update Route
- Create a new route file for editing articles, e.g.,
article/[id]/+page.server.ts
. - Load the article details:
export const load = async ({ params }) => { const article = await prisma.article.findUnique({ where: { id: Number(params.id) } }); return { article }; };
- Create a new route file for editing articles, e.g.,
-
Create Update Form
- Populate the form with the existing article details and set the action for updating:
export const actions = { updateArticle: async ({ request, params }) => { const formData = await request.formData(); const title = formData.get('title') as string; const content = formData.get('content') as string; try { await prisma.article.update({ where: { id: Number(params.id) }, data: { title, content } }); return { status: 200 }; } catch (error) { console.error(error); return { status: 500 }; } } };
- Populate the form with the existing article details and set the action for updating:
Conclusion
You have successfully built a full-stack CRUD application using SvelteKit and Prisma. You set up the environment, defined your data model, and implemented create, read, update, and delete functionalities. Next steps could include adding user authentication, deploying your application, or exploring more advanced features of SvelteKit and Prisma. Happy coding!