• SajanTech's
  • Posts
  • Kinde Authentication in Next.js: Fast and Secure Integration Guide

Kinde Authentication in Next.js: Fast and Secure Integration Guide

Boost Your Next.js App Security with Kinde Step-by-Step Authentication Setup

Introduction

Are you looking for a simple yet powerful way to manage user authentication in your Next.js 15 app? Setting up secure authentication can be one of the trickiest parts of building an application. Fortunately, Kinde makes this process much easier by providing ready-to-use tools for authentication and access management.

In this post, I’ll walk you through the steps to integrate Kinde authentication into your Next.js 15 app using the new app router configuration. Whether you’re building a scalable web app or simply tired of reinventing the authentication wheel, this guide will help you get started quickly. Let’s dive in!

Prerequisite

This guide assumes you have some experience working with Next.js. If you're new to Next.js, I highly recommend exploring the official Next.js documentation to get familiar with the basics before diving into this tutorial. It will help you better understand the concepts and configuration we'll be using.

Scaffold a Next.js Project

npx create-next-app@latest

And follow the prompt. For example, It will be something like this.

npx create-next-app@latest                  1 ↵ ──(Tue,Oct22)─┘
Need to install the following packages:
[email protected]
Ok to proceed? (y) y
✔ What is your project named? … kinde_auth
✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like your code inside a `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to use Turbopack for next dev? … No / Yes
✔ Would you like to customize the import alias (@/* by default)? … No / Yes
✔ What import alias would you like configured? … @/*

Getting Started with Kinde

Next, head over to Kinde’s website and click "Start for Free" to create your free account. The Kinde portal is incredibly user-friendly, so just follow the on-screen instructions to complete your account setup.

Curious about why Kinde is the right choice? I’ve posted a YouTube video covering all the benefits – feel free to check it out before diving in!

Installing the Kinde Auth Library

To get started, we need to install the Kinde authentication library in our Next.js project. Simply open your terminal and enter the following command:

npm i @kinde-oss/kinde-auth-nextjs

You must define an API route for Kinde to work properly. Lets do that!

Create a folder structure like below and create a file called route.ts

  • app

    • api

      • auth

        • [kindeAuth]

          • route.ts

import {handleAuth} from "@kinde-oss/kinde-auth-nextjs/server";
export const GET = handleAuth();

In the route.ts file paste the above piece of code.

This code sets up an API route in Next.js to handle authentication with Kinde.

Here’s a breakdown:

  1. Import handleAuth: The handleAuth function from the Kinde library is used to manage authentication-related operations.

  2. Define the GET Handler: By exporting GET = handleAuth(), this code configures a GET request handler for the API route. When a GET request is made to this route, handleAuth automatically manages authentication tasks, such as user login, logout, or token handling.

Create a .env.local file in the root directory and copy the environment variables from the Kinde admin section.

It should look something like this:

KINDE_CLIENT_ID=<replace with your client id>
KINDE_CLIENT_SECRET=<replace with your client secret>
KINDE_ISSUER_URL=https://<replace with your sub domain>.kinde.com
KINDE_SITE_URL=http://localhost:3000
KINDE_POST_LOGOUT_REDIRECT_URL=http://localhost:3000
KINDE_POST_LOGIN_REDIRECT_URL=http://localhost:3000

Modifying the layout.tsx File with the Code Below

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body
        className={`${geistSans.variable} ${geistMono.variable} antialiased`}
      >
        <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
          {children}
        </div>
      </body>
    </html>
  );
}

In the page.tsx file, we need to import a few components from the Kinde Auth library.

import {RegisterLink, LoginLink} from "@kinde-oss/kinde-auth-nextjs/components";
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";

With this, let's modify our page.tsx file

import Image from "next/image";
import {RegisterLink, LoginLink} from "@kinde-oss/kinde-auth-nextjs/components";
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
import { redirect } from "next/navigation";

const {isAuthenticated} =  getKindeServerSession()

export default async function Home() {
  const loggedIn = await isAuthenticated();
  if(loggedIn) return redirect('/profile');
  return (
      <main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
        <Image
          className="dark:invert"
          src="/next.svg"
          alt="Next.js logo"
          width={180}
          height={38}
          priority
        />
        
        <div className="flex gap-4 items-center flex-col sm:flex-row">
          <LoginLink
            postLoginRedirectURL="/profile"
            className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"
          >
           
           Sign In
          </LoginLink>
          <RegisterLink
            postLoginRedirectURL="/profile"
            className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44"
          >
            Sign Up
          </RegisterLink>
        </div>
      </main>
    
  );
}

Let me break down the key flow in the code above.

Imports:

  • RegisterLink and LoginLink are components from Kinde's auth library for Next.js, allowing users to sign in or register.

  • getKindeServerSession is used to manage server-side session checks.

  • redirect from Next.js is used to redirect users if they’re already logged in.

Session Check:

  • getKindeServerSession() is called to retrieve session details, specifically checking if a user is authenticated with isAuthenticated().

Authentication Redirect:

  • If loggedIn is true, the user is redirected to the /profile page, assuming they're already logged in.

Lets create a protected route. We could call it profile

Create a folder profile inside that create a file page.tsx.

import {LogoutLink} from "@kinde-oss/kinde-auth-nextjs/components";
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
import { redirect } from "next/navigation";
const {isAuthenticated, getUser} =  getKindeServerSession()

export default async function ProfilePage() {
    const loggedIn = await isAuthenticated();
    if(!loggedIn) return redirect('/')
    const user = await getUser();
    return (
        <div>
            {JSON.stringify(user, null, 4)}
            <div>
            <LogoutLink className="hover:underline">Logout</LogoutLink>
            </div>
        </div>
    )
}

This code defines a ProfilePage component that checks if a user is authenticated; if they are not, it redirects them to the home page (/), but if they are, it displays the user’s information and provides a logout link.

Note: So far, we've focused on using Kinde with server-side components. However, Kinde is also compatible with client-side components through a simple hook, making it versatile for various setups.

Unlock Seamless Client-Side Authentication in Next.js with Kinde

Inside a profile folder create a client folder under the client folder create a page.tsx and mark this component with “use client“ annotation.

"use client"

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

export default function ClientPage() {
    const {getUser} = useKindeBrowserClient();
    return <div>{JSON.stringify(getUser(), null, 3)}</div>
}

This code defines a ClientPage component that uses Kinde’s client-side authentication hook to access user information directly on the browser.

Here’s a breakdown:

  1. "use client" directive: Indicates that this is a client component in Next.js, allowing it to run on the browser rather than on the server.

  2. Import useKindeBrowserClient: This hook from Kinde’s library provides client-side methods, specifically getUser in this case.

  3. Get User Data: Within the component, getUser() retrieves the user’s data (such as profile details and authentication status) directly on the client.

  4. Render User Data: The component renders the user's information as formatted JSON within a <div>.

Overall, this setup lets you securely access and display user information directly from the client side using Kinde’s client component.

Conclusion

Integrating Kinde authentication into your Next.js 15 app doesn’t just simplify setup; it brings a powerful, scalable solution to your project’s user management needs. With Kinde, you can skip the complexities of custom authentication and focus on building the features that make your app unique.

By following the steps in this guide, you now have a secure and reliable authentication system in place, ready to scale as your application grows.

Give Kinde a try and experience firsthand how it streamlines the way you manage users in Next.js!

Stay Ahead with More Tips Like These!

If you found this guide helpful, there’s so much more where it came from! By subscribing to my blog, you'll get access to exclusive tutorials, insider tips, and all the latest updates to keep you ahead in the world of web development.

Whether you’re a seasoned developer or just starting out, each post is packed with insights designed to make your coding journey smoother and more exciting. Hit that subscribe button and join a growing community of developers leveling up their skills every day. Don’t miss out subscribe now and let’s keep building amazing things together!

Reply

or to participate.