Kinde and edge worker services
Integrations
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!
Install Prisma client and adapter dependencies with the following bash command:
npm install @prisma/client @prisma/adapter-better-sqlite3 typescript@5.9.3Prisma 7 requires TypeScript version 5.4.0 or higher. Make sure your typescript version in package.json is ^5.4.0 or higher. We are using version 5.9.3 for this guide.
Install Prisma as a dev dependency:
npm install prisma --save-devInitialize your Prisma project with SQLite as the database provider:
npx prisma init --datasource-provider sqliteIn this project, we use SQLite, a simple file-based database stored on your computer.
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.
Run migrations with the following command:
npx prisma migrate dev --name initGenerate the Prisma client with the following command:
npx prisma generateSet up Prisma Client by creating a new lib directory at the src directory of your project and adding a prisma.ts file:
mkdir src/lib && touch src/lib/prisma.tsOpen 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:
../generated/prisma/client)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.
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:
mkdir -p src/app/api/auth/success && touch src/app/api/auth/success/route.tsOpen 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:
lib/prisma.ts file.The Kinde Next.js starter kit includes a dashboard route. The code redirects to /dashboard after successful authentication. If you prefer to redirect to a different page, update the redirect URL in the route handler accordingly.
Open the .env.local file in your project and update the following environment variables:
KINDE_POST_LOGIN_REDIRECT_URL=http://localhost:3000/api/auth/successYou’re now ready to test your database integration.
Start your development server by running the following command in your terminal:
npm run devOpen your web browser and navigate to http://localhost:3000/ to view your Kinde application.
Select Sign Up to create a new user account. Enter the required details and complete the sign-up process.
Open your terminal and start the Prisma Studio by typing the following command:
npx prisma studioPrisma Studio will open in your default web browser.
Prisma Studio is a visual tool for managing your database. It provides an intuitive interface to view, edit, and manage data in your database, making it easier to inspect records and make updates without writing SQL queries. It integrates directly with your Prisma schema, streamlining database interactions during development.
In Prisma Studio, select the User model to see the newly registered user details.
You have now stored the user details in your local database using Prisma.
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.