How to connect kinde to your database (MongoDB)

When building modern web applications, integrating user authentication and securely managing your database are crucial steps. Kinde simplifies the authentication process, while MongoDB, a powerful NoSQL database, allows for flexible and scalable data storage. In this guide, I’ll walk you through the complete process of connecting Kinde to MongoDB so you can manage user authentication and data handling efficiently.

Prerequisites

Before getting started, ensure you have the following:

  • A working project set up in Next.js, since we’ll use Next.js for this integration.
  • Node.js and npm installed on your machine.
  • A basic understanding of JavaScript/TypeScript and Node.js.
  • An account set up on Kinde for authentication management.
  • A MongoDB instance running, either locally or using a cloud service like MongoDB Atlas.

Step 1: Setting Up Your MongoDB Database

If you haven’t yet set up a MongoDB instance, you can do so locally or via a cloud provider like MongoDB Atlas.

Local MongoDB Setup

  1. Install MongoDB:
    • Head over to the MongoDB official website to download the latest community version.
    • Follow the instructions specific to your operating system for installation.
  2. Run MongoDB:
    • After installation, start MongoDB by running the following command:
mongod

MongoDB should now be running on mongodb://localhost:27017.

MongoDB Atlas Setup

  1. Create a MongoDB Atlas Account:
    • Visit MongoDB Atlas and sign up for a free account.
    • Set up a new cluster by following the guided steps. Once the cluster is created, you’ll receive a connection string.
  2. Whitelisting IP Addresses:
    • Go to your cluster settings and ensure that your current IP address or any IPs accessing the database are whitelisted.
  3. Copy Your Connection String:
    • In MongoDB Atlas, find the “Connect” button, and choose “Connect your application.” Copy the provided MongoDB connection string; we’ll use it later.

Step 2: Setting Up Kinde for Authentication

Kinde provides an easy-to-integrate solution for handling user authentication. We will use their SDK to integrate with our Next.js app.

Sign Up on Kinde:

  • Go to the Kinde website and sign up for an account if you haven’t already.

Create a New Application:

  • After logging into your Kinde dashboard, create a new application. Give it a name, and choose the correct platform for your project.

Configure Your Kinde Settings:

  • After creating your app on the Kinde platform, note the Kinde domain and Client ID. You will use these in your Next.js app.
  • In your Kinde Dashboard, set up the callback URLs as per your project’s configuration. For example:
List all possible callbacks you might have to have for your project.

Install the Kinde SDK on VS Code:

  • In your Next.js project on VScode, install the Kinde SDK:
npm install @kinde-oss/kinde-auth-nextjs

Configure Kinde in Your Project:

Here’s what your source directory would look like

📦 KindeAuth
└─ src
   ├─ app
   │  └─ api
   │     ├─ protected
   │     │  └─ route.ts
   │     └─ auth
   │        ├─ [...kindeAuth]
   │        │  └─ route.ts
   │        └─ succes
   │           └─ route.ts
   └─ middleware.ts

In your src folder, create a middleware.ts file and use the following code.

import {
  authMiddleware,
  withAuth,
} from "@kinde-oss/kinde-auth-nextjs/middleware";

export default function middleware(req: Request) {
  return withAuth(req);
}

export const config = {
  matcher: ["/dashboard"],
};

In the route.ts file under your protected folder, add this code

kindeAuth > src > app > api > protected > route.ts

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

export async function GET() {
  const { getUser, isAuthenticated } = getKindeServerSession();

  if (!(await isAuthenticated())) {
    return new Response("Unauthorized", { status: 401 });
  }

  const user = await getUser();
  const data = { message: "Hello User", id: user?.given_name };

  return NextResponse.json({ data });
}

In the route.ts file under the […kindeAuth] folder, paste this code

import { handleAuth } from "@kinde-oss/kinde-auth-nextjs/server";

export const GET = handleAuth();

In the route.ts file under the success folder, paste this code

import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
import { NextResponse } from "next/server";
import User from '../../../../../models/user';
import { connectToMongoDB } from '../../../../../lib/db';

export async function GET() {
  try {

    //invoking database connection
    await connectToMongoDB();

    //getting user from the kindeSession. 
  //Note: Replace getUser() with your actual method to fetch user data from your database.
    const { getUser } = getKindeServerSession();
    const user = await getUser();


    
    if (!user || !user.id) {
      return NextResponse.json({ error: "Authentication failed" }, { status: 401 });
    }

    let dbUser = await User.findOne({ kindeId: user.id });

    if (!dbUser) {
      dbUser = await User.create({
        kindeId: user.id,
        firstName: user.given_name ?? "",
        lastName: user.family_name ?? "",
        email: user.email ?? ""
      });
    }

    // Use environment variable for redirect URL
    const redirectUrl = process.env.NEXT_PUBLIC_APP_URL ? new URL('/dashboard', process.env.NEXT_PUBLIC_APP_URL) : 'http://localhost:3000/dashboard';
    return NextResponse.redirect(redirectUrl);
  } catch (error) {
    console.error('Error in authentication:', error);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}

Add the following code to your Next.js app in a configuration file such as kinde.js or auth.js:

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *