Skip to content
  • Integrations
  • Third-party tools

Set up a Next.js app with Prisma ORM and Kinde

Learn how to integrate Kinde authentication with a Next.js application and store user data in a Prisma-managed SQLite database.

This guide will walk you through setting up the environment, installing dependencies, creating routes to handle authentication, and using Prisma Studio to view your database.

By the end, you will have a fully functional authentication flow with user management capabilities, ready to be expanded for your application’s needs. Let’s get started!

Step 1: Install Prisma in your Next.js project

Link to this section
  1. Install Prisma client and adapter dependencies with the following bash command:

    Terminal window
    npm install @prisma/client @prisma/adapter-better-sqlite3 typescript@5.9.3
  2. Install Prisma as a dev dependency:

    Terminal window
    npm install prisma --save-dev
  3. Initialize your Prisma project with SQLite as the database provider:

    Terminal window
    npx prisma init --datasource-provider sqlite

    In this project, we use SQLite, a simple file-based database stored on your computer.

  4. Open the /prisma/schema.prisma file in your code editor. Replace its contents with the following code:

    generator client {
    provider = "prisma-client"
    output = "../src/generated/prisma"
    }
    datasource db {
    provider = "sqlite"
    }
    model User {
    id Int @id @default(autoincrement())
    kindeId String @unique
    firstName String
    lastName String
    email String
    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt
    }

    The schema defines a User model with fields for id, kindeId, email, firstName, lastName, createdAt, and updatedAt, allowing the app to store user data locally.

  5. Run migrations with the following command:

    Terminal window
    npx prisma migrate dev --name init
  6. Generate the Prisma client with the following command:

    Terminal window
    npx prisma generate
  7. Set up Prisma Client by creating a new lib directory at the src directory of your project and adding a prisma.ts file:

    Terminal window
    mkdir src/lib && touch src/lib/prisma.ts
  8. Open the src/lib/prisma.ts file and copy the following code into it. Save the file after adding the code:

    import { PrismaClient } from "../generated/prisma/client";
    import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3";
    const globalForPrisma = global as unknown as {
    prisma: PrismaClient;
    };
    const adapter = new PrismaBetterSqlite3({
    url: process.env.DATABASE_URL,
    });
    const prisma: PrismaClient =
    globalForPrisma.prisma || new PrismaClient({ adapter });
    if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
    export default prisma;

    This code:

    • Imports the Prisma Client from the custom generated location (../generated/prisma/client)
    • Sets up the Better SQLite3 adapter for Prisma 7
    • Ensures that only one instance of the Prisma Client runs in your local development environment, preventing potential issues with multiple instances during hot reloading
  9. Open next.config.js (or create it if it doesn’t exist) and add the following configuration:

    /** @type {import('next').NextConfig} */
    const nextConfig = {
    webpack: (config, { isServer }) => {
    if (isServer) {
    // Fix for Prisma 7 ESM imports in Next.js
    // Resolve .js imports to .ts files in the generated Prisma client
    config.resolve.extensionAlias = {
    '.js': ['.js', '.ts', '.tsx'],
    '.jsx': ['.jsx', '.tsx'],
    };
    }
    return config;
    },
    };
    module.exports = nextConfig;

    This configuration is required for Prisma 7 to work correctly with Next.js, as Prisma 7 generates ESM-style imports with .js extensions that need to be resolved to .ts files.

Step 2: Save user data to the database after authentication

Link to this section
  1. Create a new directory named success and a route.ts file inside the src/app/api/auth/ directory by typing the following command in your terminal:

    Terminal window
    mkdir -p src/app/api/auth/success && touch src/app/api/auth/success/route.ts
  2. Open the route.ts file in your code editor, add the following code, and then save the file.

    import prisma from "@/lib/prisma"
    import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server"
    import { NextRequest, NextResponse } from "next/server"
    export async function GET(request: NextRequest) {
    try {
    const { getUser } = getKindeServerSession()
    const user = await getUser()
    if (!user || !user.id) {
    return NextResponse.json(
    { error: "Unauthorized" },
    { status: 401 }
    )
    }
    // Check if user already exists in database
    let dbUser = await prisma.user.findUnique({
    where: { kindeId: user.id },
    })
    // Create user if they don't exist
    if (!dbUser) {
    dbUser = await prisma.user.create({
    data: {
    kindeId: user.id,
    firstName: user.given_name ?? "",
    lastName: user.family_name ?? "",
    email: user.email ?? "",
    },
    })
    }
    // Redirect to dashboard after successful authentication
    const origin = request.nextUrl.origin
    return NextResponse.redirect(`${origin}/dashboard`)
    } catch (error) {
    console.error("Error in auth success route:", error)
    return NextResponse.json(
    { error: "Internal server error" },
    { status: 500 }
    )
    }
    }

    When the code runs, it:

    • Imports the Prisma instance from the lib/prisma.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 creates a new user record if not.
    • Includes proper error handling and uses environment variables for the redirect URL.
  3. Open the .env.local file in your project and update the following environment variables:

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

You’re now ready to test your database integration.

Step 3: Test the Prisma integration

Link to this section
  1. Start your development server by running the following command in your terminal:

    Terminal window
    npm run dev
  2. Open your web browser and navigate to http://localhost:3000/ to view your Kinde application.

  3. Select Sign Up to create a new user account. Enter the required details and complete the sign-up process.

  4. Open your terminal and start the Prisma Studio by typing the following command:

    Terminal window
    npx prisma studio

    Prisma Studio will open in your default web browser.

  5. In Prisma Studio, select the User model to see the newly registered user details.

    prisma studio

You have now stored the user details in your local database using Prisma.

Congratulations

Link to this section

You’ve successfully set up Kinde authentication with your Next.js application and integrated it with Prisma for user management. You’ve also configured Prisma Studio to easily view and manage your database.

With the user data now stored in your local database, you can build further features and enhance your application as needed.