-
Notifications
You must be signed in to change notification settings - Fork 830
Added Prisma Postgres guide to docs/integrations/databases/
#2465
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
aidankmcalister
wants to merge
8
commits into
clerk:main
Choose a base branch
from
aidankmcalister:prisma-postgres-added-to-integrations
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
6595e2e
Added Prisma Postgres
aidankmcalister d0f253f
Merge branch 'main' into prisma-postgres-added-to-integrations
aidankmcalister 5448167
Merge branch 'main' into prisma-postgres-added-to-integrations
aidankmcalister 0c4d05c
Merge branch 'main' into prisma-postgres-added-to-integrations
aidankmcalister e8c5086
Merge branch 'main' into prisma-postgres-added-to-integrations
aidankmcalister b675dc0
changes based on PR comments and latest Prisma updates
aidankmcalister f924764
highlighting adjusted
aidankmcalister e2145ef
remove next app creation
aidankmcalister File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,196 @@ | ||
--- | ||
title: Integrate Prisma Postgres with Clerk | ||
description: Learn how to integrate Clerk into your Prisma Postgres application. | ||
--- | ||
|
||
<TutorialHero | ||
beforeYouStart={[ | ||
{ | ||
title: "Set up a Clerk application", | ||
link: "/docs/quickstarts/setup-clerk", | ||
icon: "clerk", | ||
} | ||
]} | ||
/> | ||
|
||
This tutorial shows you how to build a Next.js application with Clerk authentication and Prisma Postgres. You'll create a simple messaging app where users can store and manage their personal messages using Prisma ORM for database operations. | ||
|
||
<Steps> | ||
## Create a new Next.js project | ||
|
||
1. Create a new Next.js project using the following command: | ||
```sh {{ filename: 'terminal' }} | ||
npx create-next-app clerk-prisma-example --typescript --eslint --tailwind --use-npm --no-src-dir --app --import-alias "@/*" | ||
``` | ||
1. Navigate to the project directory and install the required dependencies: | ||
```sh {{ filename: 'terminal' }} | ||
cd clerk-prisma-example | ||
npm install prisma --save-dev | ||
npm install tsx --save-dev | ||
npm install @prisma/extension-accelerate | ||
``` | ||
|
||
## Integrate the Next.js Clerk SDK | ||
|
||
Follow the [Next.js quickstart](/docs/quickstarts/nextjs) to integrate the Clerk Next.js SDK into your application. | ||
|
||
## Protect your application routes | ||
|
||
To ensure that only authenticated users can access your application, modify [`clerkMiddleware`](/docs/references/nextjs/clerk-middleware) to require authentication for every route. | ||
|
||
```typescript {{ filename: 'middleware.ts', mark: [[3, 5]] }} | ||
import { clerkMiddleware } from '@clerk/nextjs/server' | ||
|
||
export default clerkMiddleware(async (auth) => { | ||
await auth.protect() | ||
}) | ||
|
||
export const config = { | ||
matcher: [ | ||
// Skip Next.js internals and all static files, unless found in search params | ||
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)', | ||
// Always run for API routes | ||
'/(api|trpc)(.*)', | ||
], | ||
} | ||
``` | ||
|
||
## Set up the application schema and database connection | ||
|
||
Next, you'll need to initialize Prisma and set up a Prisma Postgres database. | ||
|
||
1. Initialize Prisma in your project: | ||
```sh {{ filename: 'terminal' }} | ||
npx prisma init --output ../app/generated/prisma | ||
``` | ||
|
||
After initializing Prisma, your environment variable file should have the following values: | ||
|
||
```env {{ filename: '.env' }} | ||
DATABASE_URL=PRISMA_POSTGRES_CONNECTION_STRING | ||
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY={{pub_key}} | ||
CLERK_SECRET_KEY={{secret}} | ||
``` | ||
|
||
1. Create a `schema.prisma` file in the `prisma/` directory that defines the database schema. The schema will include a table called `user_messages` with the columns `user_id`, `create_ts`, and `message`. The `user_id` column will be used to store the user's Clerk ID. | ||
|
||
```prisma {{ filename: 'prisma/schema.prisma' }} | ||
generator client { | ||
provider = "prisma-client-js" | ||
output = "../app/generated/prisma" | ||
} | ||
|
||
datasource db { | ||
provider = "postgresql" | ||
url = env("DATABASE_URL") | ||
} | ||
|
||
model UserMessage { | ||
user_id String @id | ||
create_ts DateTime @default(now()) | ||
message String | ||
} | ||
``` | ||
aidankmcalister marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
1. Create a reusable Prisma Client instance in `lib/prisma.ts`: | ||
|
||
```typescript {{ filename: 'lib/prisma.ts' }} | ||
import { PrismaClient } from '../app/generated/prisma' | ||
|
||
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 | ||
|
||
export default prisma | ||
``` | ||
|
||
## Push the schema to the database | ||
|
||
Run the following command to push the schema to the database: | ||
|
||
```sh {{ filename: 'terminal' }} | ||
npx prisma db push | ||
aidankmcalister marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
``` | ||
|
||
## Create Server Actions to handle user interactions | ||
|
||
To handle form submissions for adding and deleting user messages, create two Server Actions in `app/actions.ts`. Use Clerk's [`auth()` helper](/docs/references/nextjs/auth) to obtain the user ID, which will be used to interact with the database. | ||
|
||
```typescript {{ filename: 'app/actions.ts' }} | ||
'use server' | ||
|
||
import { auth } from '@clerk/nextjs/server' | ||
import prisma from '@/lib/prisma' | ||
|
||
export async function createUserMessage(formData: FormData) { | ||
const { userId } = await auth() | ||
if (!userId) throw new Error('User not found') | ||
|
||
const message = formData.get('message') as string | ||
await prisma.userMessage.create({ | ||
data: { | ||
user_id: userId, | ||
message, | ||
}, | ||
}) | ||
} | ||
|
||
export async function deleteUserMessage() { | ||
const { userId } = await auth() | ||
if (!userId) throw new Error('User not found') | ||
|
||
await prisma.userMessage.deleteMany({ | ||
where: { user_id: userId }, | ||
}) | ||
} | ||
aidankmcalister marked this conversation as resolved.
Show resolved
Hide resolved
|
||
``` | ||
|
||
## Create the UI for the Home Page | ||
|
||
In your `app/page.tsx` file, add the following code to create the UI for the home page. If a message exists, the user can view and delete it; otherwise, they can add a new message. | ||
|
||
To retrieve the user's messages, use Clerk's [`auth()` helper](/docs/references/nextjs/auth) to obtain the user's ID. Then, use this ID to query the database for the user's messages. | ||
|
||
To enable the user to delete or add a message, use the `deleteUserMessage()` and `createUserMessage()` actions created in the previous step. | ||
|
||
```tsx {{ filename: 'app/page.tsx' }} | ||
import { createUserMessage, deleteUserMessage } from './actions' | ||
import prisma from '@/lib/prisma' | ||
import { auth } from '@clerk/nextjs/server' | ||
|
||
export default async function Home() { | ||
const { userId } = await auth() | ||
if (!userId) throw new Error('User not found') | ||
const existingMessage = await prisma.userMessage.findUnique({ | ||
where: { user_id: userId }, | ||
}) | ||
|
||
return ( | ||
<main> | ||
<h1>Prisma + Clerk Example</h1> | ||
{existingMessage ? ( | ||
<div> | ||
<p>{existingMessage.message}</p> | ||
<form action={deleteUserMessage}> | ||
<button>Delete Message</button> | ||
</form> | ||
</div> | ||
) : ( | ||
<form action={createUserMessage}> | ||
<input type="text" name="message" placeholder="Enter a message" /> | ||
<button>Save Message</button> | ||
</form> | ||
)} | ||
</main> | ||
) | ||
} | ||
``` | ||
|
||
## Run the application | ||
|
||
Run your application and open `http://localhost:3000` in your browser. Sign in with Clerk and interact with the application to add and delete user messages. | ||
</Steps> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.