Skip to content

Conversation

@tamalchowdhury
Copy link
Collaborator

@tamalchowdhury tamalchowdhury commented Nov 12, 2025

next.js and prisma integration guide

Related issues & labels (optional)

  • Adds a new integration guide

Summary by CodeRabbit

  • Documentation
    • Added comprehensive integration guide for Kinde authentication with Next.js applications using Prisma ORM and SQLite. Covers app setup, schema configuration, client implementation, API route creation for user storage and authentication, callback URL setup, environment variable configuration, and testing procedures with code examples and visual references.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 12, 2025

Walkthrough

A new MDX documentation file was added providing a comprehensive step-by-step integration guide for Kinde authentication with Next.js, Prisma ORM, and SQLite, including setup instructions, code examples, environment configuration, and testing procedures.

Changes

Cohort / File(s) Change Summary
Kinde + Next.js + Prisma Integration Documentation
src/content/docs/integrate/third-party-tools/kinde-nextjs-prisma.mdx
New documentation file added with front matter metadata and detailed integration guide including Kinde app setup, Prisma initialization, User schema configuration, Prisma Client instantiation pattern, API route for user authentication and database persistence, environment variable setup, callback URL configuration, and integration testing steps.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant NextJS as Next.js App
    participant Kinde as Kinde Auth
    participant PrismaDB as Prisma + SQLite
    
    User->>NextJS: Click login
    NextJS->>Kinde: Redirect to Kinde
    User->>Kinde: Authenticate
    Kinde->>NextJS: Redirect to /api/auth/success
    rect rgba(100, 200, 100, 0.2)
        Note over NextJS,PrismaDB: User persistence flow (new)
        NextJS->>NextJS: Extract user data from Kinde
        NextJS->>PrismaDB: Upsert user record
        PrismaDB->>NextJS: User stored/updated
    end
    NextJS->>User: Redirect to dashboard
Loading

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

  • Primarily documentation content; verify code examples are accurate and complete
  • Confirm all Kinde, Prisma, and Next.js configurations are up-to-date with current versions

Poem

🐰 A guide hops into view, so clear and so bright,
Kinde meets Next.js, now perfectly right!
With Prisma and SQLite dancing as one,
Auth integration's simplified—let's have some fun! 🎉

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding a Next.js and Prisma integration guide documentation file.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch tamal/feat/kinde-prisma-orm

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Nov 12, 2025

Deploying kinde-docs-preview with  Cloudflare Pages  Cloudflare Pages

Latest commit: a7448c7
Status: ✅  Deploy successful!
Preview URL: https://f8ceeaa2.kinde-docs-preview.pages.dev
Branch Preview URL: https://tamal-feat-kinde-prisma-orm.kinde-docs-preview.pages.dev

View logs

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
src/content/docs/integrate/third-party-tools/kinde-nextjs-prisma.mdx (4)

80-97: Use prisma code block language for better syntax highlighting.

The Prisma schema is currently wrapped in a yaml code block, which may not highlight the schema correctly. Use prisma instead for proper syntax highlighting.

-    ```yaml
+    ```prisma
     generator client {
       provider = "prisma-client-js"
     }
     
     datasource db {
       provider = "sqlite"
       url      = env("DATABASE_URL")
     }
     
     model User {
       id        Int    @id @default(autoincrement())
       kindeId   String @unique
       email     String @unique
       firstName String
       lastName  String
     }
-    ```
+    ```

162-191: Add error handling for database constraint violations.

The route handler throws a generic error if the user is missing data, but doesn't handle the case where the email or kindeId already exists (unique constraint violations). Add try/catch logic to provide better error handling and recovery.

Consider wrapping the create operation in a try/catch block to handle Prisma.PrismaClientKnownRequestError for unique constraint violations, and gracefully retry with an update instead.


115-115: Tighten the wording for clarity.

The sentence is slightly wordy. Consider shortening it to improve readability:

-Remember to run these commands every time you make changes to the `schema.prisma` file to keep your database and Prisma Client in sync.
+Run these commands whenever you update `schema.prisma` to keep your database and Prisma Client in sync.

248-248: Use more distinctive phrasing to enhance the tone.

The phrase "Feel free to explore" is informal. Consider a more professional alternative:

-Feel free to explore more of [Prisma's](https://www.prisma.io/) capabilities and continue to refine your application's authentication and database integration.
+Explore [Prisma's](https://www.prisma.io/) capabilities further and continue to refine your application's authentication and database integration.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7c0b30c and 344fbd1.

📒 Files selected for processing (1)
  • src/content/docs/integrate/third-party-tools/kinde-nextjs-prisma.mdx (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-11-12T06:00:08.396Z
Learnt from: marcosmartini
Repo: kinde-oss/documentation PR: 253
File: src/content/docs/properties/work-with-properties/property-groups.mdx:13-13
Timestamp: 2024-11-12T06:00:08.396Z
Learning: In the project documentation, the `/kinde-apis/management` and `/kinde-apis/frontend` pages use a third-party API reference and client that loads a Single Page Application (SPA). Therefore, links to sections within these pages are valid, even if they appear to point to non-existent sections in static analysis, and should not be flagged.

Applied to files:

  • src/content/docs/integrate/third-party-tools/kinde-nextjs-prisma.mdx
🪛 LanguageTool
src/content/docs/integrate/third-party-tools/kinde-nextjs-prisma.mdx

[style] ~115-~115: Consider shortening or rephrasing this to strengthen your wording.
Context: ...er to run these commands every time you make changes to the schema.prisma file to keep your d...

(MAKE_CHANGES)


[style] ~248-~248: Consider using a less common alternative to make your writing sound more unique and professional.
Context: ...nd enhance your application as needed. Feel free to explore more of [Prisma's](https://www....

(FEEL_FREE_TO_STYLE_ME)

🔇 Additional comments (1)
src/content/docs/integrate/third-party-tools/kinde-nextjs-prisma.mdx (1)

59-67: Verify PackageManagers component implementation & rendering

Found MDX usages (src/content/docs/integrate/third-party-tools/kinde-nextjs-prisma.mdx — lines ~61,63) and a docs entry describing PackageManagers (public/_llms-full.txt), but I could not find the component implementation in the repo. Confirm the PackageManagers component exists (or which plugin provides it) and that it renders the correct npm / pnpm / yarn install commands for pkg='prisma -D' and pkg='@prisma/client'.

Comment on lines 144 to 211
## Step 3: Save user data to the database after authentication

1. Create a new directory named `success` inside the **src/app/api/auth/** directory by typing the following command in your terminal:

```bash
mkdir src/app/api/auth/success
```

2. Create a `route.ts` file inside the newly created directory by running the following command.

This file will act as a GET route to interface with the database and handle user authentication data.

```bash
touch src/app/api/auth/success/route.ts
```

3. Open the `route.ts` file in your code editor, add the following code, and then save the file.

```tsx
import prisma from "@/db";
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
import { NextResponse } from "next/server";

export async function GET() {
const { getUser } = getKindeServerSession();
const user = await getUser();

if (!user || user == null || !user.id)
throw new Error("something went wrong with authentication" + user);

let dbUser = await prisma.user.findUnique({
where: { kindeId: user.id },
});

if (!dbUser) {
dbUser = await prisma.user.create({
data: {
kindeId: user.id,
firstName: user.given_name ?? "",
lastName: user.family_name ?? "",
email: user.email ?? "", // Using nullish coalescing operator to provide a default empty string value
},
});
}

return NextResponse.redirect("http://localhost:3000/dashboard");
}
```

When the code runs, it:

- Imports the Prisma instance from the `db.ts` file.
- Imports functions to interact with the Kinde Server Session and handle the Next.js response.
- Defines a **GET** route to retrieve the authenticated user's information.
- Checks if the user is already stored in the database and updates the database with user information if not.
4. Open the `.env` file in your project and update the `KINDE_POST_LOGIN_REDIRECT_URL` field with the following value:

```tsx
KINDE_POST_LOGIN_REDIRECT_URL=http://localhost:3000/api/auth/success
```

This ensures that after a successful login, the user is redirected to this route, which updates the database and then redirects the user.

5. Go to the **Details** page of your Kinde dashboard and add `http://localhost:3000/api/auth/success` to the list of **Callback URLs.**
6. Select **Save**.

![callback urls](https://imagedelivery.net/skPPZTHzSlcslvHjesZQcQ/05d49ca9-edfc-4ac0-e141-a52fa94bac00/public)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Add guidance for creating the /dashboard route.

The guide redirects users to /dashboard after authentication but never explains how to create this page. Users will encounter a 404 error when following this guide.

Add a brief section after Step 3 (or at the end of Step 3) showing how to create a basic dashboard page. At minimum, include:

  • Instructions to create src/app/dashboard/page.tsx
  • A basic component that displays the logged-in user or a success message
  • Mention this is a placeholder and can be customized
🤖 Prompt for AI Agents
In src/content/docs/integrate/third-party-tools/kinde-nextjs-prisma.mdx around
lines 144 to 211, the guide redirects users to /dashboard but never shows how to
create that page; add a short subsection immediately after Step 3 instructing
readers to create src/app/dashboard/page.tsx, describing that the file should
export a basic React Server Component (or client component if preferred) which
displays the logged-in user info or a simple success/welcome message, note that
this is a placeholder that can be customized, and include a brief instruction to
protect or extend the page to fetch the authenticated user when integrating with
Kinde.

3. Open the `route.ts` file in your code editor, add the following code, and then save the file.

```tsx
import prisma from "@/db";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Fix import/export mismatch that will cause runtime errors.

The import statement uses a default import, but db.ts exports a named export. This will result in prisma being undefined at runtime.

-import prisma from "@/db";
+import { prisma } from "@/db";
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import prisma from "@/db";
import { prisma } from "@/db";
🤖 Prompt for AI Agents
In src/content/docs/integrate/third-party-tools/kinde-nextjs-prisma.mdx around
line 163, the file currently uses a default import (import prisma from "@/db")
but db.ts exports a named export, causing prisma to be undefined at runtime;
update the import to use the named export (import { prisma } from "@/db") or
alternatively adjust db.ts to export default prisma so the import and export
match, then rebuild and verify no runtime import errors.

});
}

return NextResponse.redirect("http://localhost:3000/dashboard");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Replace hardcoded redirect URL with environment variable.

The redirect is hardcoded to http://localhost:3000/dashboard, which will break in production and staging environments. Use an environment variable instead.

-  return NextResponse.redirect("http://localhost:3000/dashboard");
+  return NextResponse.redirect(new URL("/dashboard", process.env.APP_URL || "http://localhost:3000"));

Then add the environment variable to the .env configuration step (around line 199).

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return NextResponse.redirect("http://localhost:3000/dashboard");
return NextResponse.redirect(new URL("/dashboard", process.env.APP_URL || "http://localhost:3000"));
🤖 Prompt for AI Agents
In src/content/docs/integrate/third-party-tools/kinde-nextjs-prisma.mdx around
line 189 the redirect is hardcoded to "http://localhost:3000/dashboard"; replace
this with a call to an environment variable (e.g.,
process.env.NEXT_PUBLIC_APP_URL or NEXT_PUBLIC_DASHBOARD_URL) concatenated with
"/dashboard" so deployments use the correct base URL, and update the .env
configuration section near line 199 to document and include that environment
variable with an example value for local development.

@tamalchowdhury tamalchowdhury marked this pull request as draft November 12, 2025 13:22
@tamalchowdhury tamalchowdhury changed the title feat: next.js and prisma integration guide feat: guide - next.js and prisma integratio Nov 13, 2025
@tamalchowdhury tamalchowdhury changed the title feat: guide - next.js and prisma integratio feat: guide - next.js and prisma integration Nov 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants