Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
295 changes: 295 additions & 0 deletions docs/guides/development/integrations/databases/prisma-postgres.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,295 @@
---
title: Integrate Prisma Postgres with Clerk
description: Learn how to integrate Clerk into your Prisma Postgres application.
---

<TutorialHero
beforeYouStart={[
{
title: "Follow the Next.js quickstart",
link: "/docs/nextjs/getting-started/quickstart",
icon: "nextjs",
}
]}
/>

Integrating Prisma Postgres with Clerk gives you the benefits of using a Prisma Postgres database while leveraging Clerk's authentication, prebuilt components, and webhooks. This guide will show you how to create a simple blog application that allows users to create and read posts using Prisma Postgres and Clerk. This guide uses Next.js App Router but the same principles can be applied to other SDKs.

<Steps>
## Install Prisma

Run the following command to install Prisma:

```sh {{ filename: 'terminal' }}
npm install prisma tsx --save-dev
```

## Initialize Prisma

Run the following command to initialize Prisma:

```sh {{ filename: 'terminal' }}
npx prisma init --output ../app/generated/prisma
```

This will:

- Create a new `prisma/` directory in your project, with a `schema.prisma` file inside of it. The `schema.prisma` file is where you will define your database models.
- Create a `prisma.config.ts` file in the root of your project.
- Update your `.env` file to include a `DATABASE_URL` environment variable, which is used to store your database connection string for your Prisma Postgres database.

## Update the Prisma configuration

Inside the `prisma.config.ts` file, add `import "dotenv/config";` so that it can load the `DATABASE_URL` environment variable from your `.env` file.

```ts {{ filename: 'prisma.config.ts', mark: [1] }}
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'

export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
engine: 'classic',
datasource: {
url: env('DATABASE_URL'),
},
})
```

## Update the database schema

In the `prisma/schema.prisma` file, update the schema to include a new model called `Post` with the columns `id`, `title`, `content`, `published`, and `authorId`. The `id` column will be used as the post's primary key, and the `authorId` column will be used to store the user's Clerk ID.

```prisma {{ filename: 'prisma/schema.prisma', mark: [[11, 17]] }}
generator client {
provider = "prisma-client"
output = "../app/generated/prisma"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
authorId String
}
```

## Push the schema to the database

Run the following command to push the updated schema to the database:

```sh {{ filename: 'terminal' }}
npx prisma db push
```

## Create a reusable Prisma Client instance

At the root of your project, create a folder called `lib`. Inside of it, create a new file called `prisma.ts` and add the following code to it. This will set up a single Prisma Client instance, which is used to interact with your database, and bind it to the global object so that only one instance of the client is created in your application. This helps resolve issues with hot reloading that can occur when using Prisma with Next.js in development mode.

```typescript {{ filename: 'lib/prisma.ts' }}
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

const globalForPrisma = global as unknown as { prisma: typeof prisma }

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma

export default prisma
```

## Create the UI for the homepage

Now that all of the set up is complete, it's time to start building out your app.

Replace the contents of `app/page.tsx` with the following code. This page fetches all posts from your database and displays them on the homepage, showing the title and author ID for each post. It uses the [`prisma.post.findMany()`](https://www.prisma.io/docs/orm/reference/prisma-client-reference?utm_source=docs#findmany) method, which is a Prisma Client method that retrieves all records from the database.

```tsx {{ filename: 'app/page.tsx' }}
import Link from 'next/link'
import prisma from '@/lib/prisma'

export default async function Page() {
const posts = await prisma.post.findMany() // Query the `Post` model for all posts

return (
<div className="mx-auto mt-8 flex min-h-screen max-w-2xl flex-col">
<h1 className="mb-8 text-4xl font-bold">Posts</h1>

<div className="mb-8 flex max-w-2xl flex-col space-y-4">
{posts.map((post) => (
<Link
key={post.id}
href={`/posts/${post.id}`}
className="hover:bg-neutral-100 dark:hover:bg-neutral-800 flex flex-col rounded-lg px-2 py-4 transition-all hover:underline"
>
<span className="text-lg font-semibold">{post.title}</span>
<span className="text-sm">by {post.authorId}</span>
</Link>
))}
</div>

<Link
href="/posts/create"
className="inline-block rounded-lg border-2 border-current px-4 py-2 text-current transition-all hover:scale-[0.98]"
>
Create New Post
</Link>
</div>
)
}
```

## Create a new post

Create a new file called `app/posts/create/page.tsx` and add the following code to it. This page allows users to create new posts. It uses Clerk's [`auth`](/docs/reference/backend/types/auth-object) object to get the user's ID.

- If there is no user ID, the user is not signed in, so a sign in button is displayed.
- If the user is signed in, the "Create New Post" form is displayed. When the form is submitted, the `createPost()` function is called. This function creates a new post in the database using the [`prisma.post.create()`](https://www.prisma.io/docs/orm/reference/prisma-client-reference?utm_source=docs#create) method, which is a Prisma Client method that creates a new record in the database.

```tsx {{ filename: 'app/posts/create/page.tsx' }}
import Form from 'next/form'
import prisma from '@/lib/prisma'
import { redirect } from 'next/navigation'
import { SignInButton, useAuth } from '@clerk/nextjs'
import { revalidatePath } from 'next/cache'
import { auth } from '@clerk/nextjs/server'

export default async function NewPost() {
// The `Auth` object gives you access to properties like `userId`
// Accessing the `Auth` object differs depending on the SDK you're using
// https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object
const { userId } = await auth()

// Protect this page from unauthenticated users
if (!userId) {
return (
<div className="flex h-[calc(100vh-4rem)] flex-col items-center justify-center space-y-4">
<p>You must be signed in to create a post.</p>
<SignInButton>
<button
type="submit"
className="inline-block cursor-pointer rounded-lg border-2 border-current px-4 py-2 text-current transition-all hover:scale-[0.98]"
>
Sign in
</button>
</SignInButton>
</div>
)
}

async function createPost(formData: FormData) {
'use server'

// Type check
if (!userId) return

const title = formData.get('title') as string
const content = formData.get('content') as string

await prisma.post.create({
data: {
title,
content,
authorId: userId,
},
})

revalidatePath('/')
redirect('/')
}

return (
<div className="mx-auto max-w-2xl p-4">
<h1 className="mb-6 text-2xl font-bold">Create New Post</h1>
<Form action={createPost} className="space-y-6">
<div>
<label htmlFor="title" className="mb-2 block text-lg">
Title
</label>
<input
type="text"
id="title"
name="title"
placeholder="Enter your post title"
className="w-full rounded-lg border px-4 py-2"
/>
</div>
<div>
<label htmlFor="content" className="mb-2 block text-lg">
Content
</label>
<textarea
id="content"
name="content"
placeholder="Write your post content here..."
rows={6}
className="w-full rounded-lg border px-4 py-2"
/>
</div>
<button
type="submit"
className="inline-block w-full rounded-lg border-2 border-current px-4 py-2 text-current transition-all hover:scale-[0.98]"
>
Create Post
</button>
</Form>
</div>
)
}
```

## Query a single record

Create a new file called `app/posts/[id]/page.tsx` and add the following code to it. This page uses the URL parameters to get the post's ID, and then fetches it from your database and displays it on the page, showing the title, author ID, and content. It uses the [`prisma.post.findUnique()`](https://www.prisma.io/docs/orm/reference/prisma-client-reference?utm_source=docs#findunique) method, which is a Prisma Client method that retrieves a single record from the database.

```tsx {{ filename: 'app/posts/[id]/page.tsx' }}
import prisma from '@/lib/prisma'

export default async function Post({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const post = await prisma.post.findUnique({
where: { id: parseInt(id) },
})

if (!post) {
return (
<div className="mx-auto mt-8 flex min-h-screen max-w-2xl flex-col">
<div>No post found.</div>
</div>
)
}

return (
<div className="mx-auto mt-8 flex min-h-screen max-w-2xl flex-col">
{post && (
<article className="w-full max-w-2xl">
<h1 className="mb-2 text-2xl font-bold sm:text-3xl md:text-4xl">{post.title}</h1>
<p className="text-sm sm:text-base">by {post.authorId}</p>
<div className="prose prose-gray prose-sm sm:prose-base lg:prose-lg mt-4 sm:mt-8">
{post.content || 'No content available.'}
</div>
</article>
)}
</div>
)
}
```

## Test your app

Run your application with the following command:

```sh {{ filename: 'terminal' }}
npm run dev
```

Visit your application at `http://localhost:3000`. Sign in with Clerk and interact with the application to create and read posts. You should be able to see the posts you created on the homepage, and select a single post to view it.
</Steps>
6 changes: 6 additions & 0 deletions docs/guides/development/integrations/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ description: Learn about the available integrations with Clerk.

---

- [Prisma Postgres](/docs/guides/development/integrations/databases/prisma-postgres)
- Build applications using Prisma Postgres with Clerk as your authentication provider.
- {<svg width="58" height="72" viewBox="0 0 58 72" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M0.522473 45.0933C-0.184191 46.246 -0.173254 47.7004 0.550665 48.8423L13.6534 69.5114C14.5038 70.8529 16.1429 71.4646 17.6642 71.0082L55.4756 59.6648C57.539 59.0457 58.5772 56.7439 57.6753 54.7874L33.3684 2.06007C32.183 -0.511323 28.6095 -0.722394 27.1296 1.69157L0.522473 45.0933ZM32.7225 14.1141C32.2059 12.9187 30.4565 13.1028 30.2001 14.3796L20.842 60.9749C20.6447 61.9574 21.5646 62.7964 22.5248 62.5098L48.6494 54.7114C49.4119 54.4838 49.8047 53.6415 49.4891 52.9111L32.7225 14.1141Z" fill="white"/></svg>}

---

- [Shopify](/docs/guides/development/integrations/platforms/shopify)
- Use Clerk as your preferred Auth solution for your Shopify store.
- {<svg width="32" height="32" viewBox="0 0 292 292" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid"><path d="M223.774 57.34c-.201-1.46-1.48-2.268-2.537-2.357-1.055-.088-23.383-1.743-23.383-1.743s-15.507-15.395-17.209-17.099c-1.703-1.703-5.029-1.185-6.32-.805-.19.056-3.388 1.043-8.678 2.68-5.18-14.906-14.322-28.604-30.405-28.604-.444 0-.901.018-1.358.044C129.31 3.407 123.644.779 118.75.779c-37.465 0-55.364 46.835-60.976 70.635-14.558 4.511-24.9 7.718-26.221 8.133-8.126 2.549-8.383 2.805-9.45 10.462C21.3 95.806.038 260.235.038 260.235l165.678 31.042 89.77-19.42S223.973 58.8 223.775 57.34zM156.49 40.848l-14.019 4.339c.005-.988.01-1.96.01-3.023 0-9.264-1.286-16.723-3.349-22.636 8.287 1.04 13.806 10.469 17.358 21.32zm-27.638-19.483c2.304 5.773 3.802 14.058 3.802 25.238 0 .572-.005 1.095-.01 1.624-9.117 2.824-19.024 5.89-28.953 8.966 5.575-21.516 16.025-31.908 25.161-35.828zm-11.131-10.537c1.617 0 3.246.549 4.805 1.622-12.007 5.65-24.877 19.88-30.312 48.297l-22.886 7.088C75.694 46.16 90.81 10.828 117.72 10.828z" fill="#95BF46"/><path d="M221.237 54.983c-1.055-.088-23.383-1.743-23.383-1.743s-15.507-15.395-17.209-17.099c-.637-.634-1.496-.959-2.394-1.099l-12.527 256.233 89.762-19.418S223.972 58.8 223.774 57.34c-.201-1.46-1.48-2.268-2.537-2.357" fill="#5E8E3E"/><path d="M135.242 104.585l-11.069 32.926s-9.698-5.176-21.586-5.176c-17.428 0-18.305 10.937-18.305 13.693 0 15.038 39.2 20.8 39.2 56.024 0 27.713-17.577 45.558-41.277 45.558-28.44 0-42.984-17.7-42.984-17.7l7.615-25.16s14.95 12.835 27.565 12.835c8.243 0 11.596-6.49 11.596-11.232 0-19.616-32.16-20.491-32.16-52.724 0-27.129 19.472-53.382 58.778-53.382 15.145 0 22.627 4.338 22.627 4.338" fill="#FFF"/></svg>}
Expand Down
4 changes: 4 additions & 0 deletions docs/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -886,6 +886,10 @@
"title": "Nhost",
"href": "/docs/guides/development/integrations/databases/nhost"
},
{
"title": "Prisma Postgres",
"href": "/docs/guides/development/integrations/databases/prisma-postgres"
},
{
"title": "Supabase",
"href": "/docs/guides/development/integrations/databases/supabase"
Expand Down