NextJs 14 + Kinde Setup | Authentication/Authorization
Tags: nextjs, webdev, kinde, tutorial
Published: 2024-05-12 22:04:14


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wc6pksm9i28cvvvjp43q.jpg)

The 90% of the websites uses some kind of authentication or authorization. Such as Facebook, Instagram, Google etc. In some point this kind of solution is inevitable to use in your website or service.

This guide will show you Kinde's auth service, that you can setup in minutes.

**Requirements:**

- NextJS 13 or higher
- Kinde auth
- that's it, simple

**What Kinde offers you:**

- Easy login/signup with many socials (Google, Apple, Slack…)
- Multi-factor auth (MFA)
- Password and passwordless auth
- Dashboard (managing users)
- Site protection/authorization
- And so many great things…

Let's get started. I'm going to show you how can you setup Kinde in NextJS environment in few steps.

1. Create a new NextJS Project:

```
npx create-next-app@latest
```

> Choose './src' directory option

Finally your project's folder strcuture is going to be look like this ->

```
/public
/src
  /app
next.config.js
.gitignore

and more.. but these are the important right now.
```

2. Install Kinde with NPM (also works with YARN)

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

3. Create '.env' file and copy-paste environment variables

- Go to Admin -> [Your application] -> Details -> Quick start -> Scroll down a little bit

You will find something like this with your keys:

```
KINDE_CLIENT_ID=""
KINDE_CLIENT_SECRET=""
KINDE_ISSUER_URL=""
KINDE_SITE_URL=http://localhost:3000
KINDE_POST_LOGOUT_REDIRECT_URL=http://localhost:3000
KINDE_POST_LOGIN_REDIRECT_URL=http://localhost:3000/dashboard
```

- Now, let's create a '.env' file in the root of your project file
- Copy-paste the variables

> You should also include '.env' file in your '.gitignore' file

4. Using the API

Now, you must create a route file in your API folder, to handle all the routing

How can you do that? Let me show you:

- In your '/app' folder create an '/api' folder
- Then, in your '/api' folder create '/auth' folder
- Next, in your '/auth' folder create an another folder called '[kindeAuth]'
- And last but not least, create in this folder a 'route.js' file and copy paste this code:

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

If you followed the steps right, you will get this structure:

```
/app
  /api
    /auth
      /[kindeAuth]
        route.js
```

Basically, we almost finished all the configuration, we:

- Created a NextJS project
- Installed Kinde library
- Copy-pasted the envarionment variables
- Setup a route file

> And there is one extra configuration which will be save a lot of headaches from you.

- Go to your 'next.config.js' file
- And include this code in your nextConfig object:

```
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "lh3.googleusercontent.com",
      },
    ],
  },
};

module.exports = nextConfig;
```

> It will be important, when you try to login with Google. (If you want to use other platforms, you also have to include its pattern here.)

## And now let's make a simple login/logout and signup application.

Let's import the necessary functions and components.

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

> Note: getKindeServerSession is a server function, you won't be able to use in client component.

Look at this basic example:

```
import "./globals.css";
import {
  RegisterLink,
  LoginLink,
  LogoutLink,
} from "@kinde-oss/kinde-auth-nextjs/components";
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
import Link from "next/link";

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {

  const { isAuthenticated, getUser } = getKindeServerSession();
  const user = await getUser();

  return (
    <html lang="en">
      <body>
        <header>
          <nav className="nav container">
            <h1 className="text-display-3">KindeAuth</h1>
            <div>
              {!(await isAuthenticated()) ? (
                <>
                  <LoginLink className="btn btn-ghost sign-in-btn">
                    Sign in
                  </LoginLink>
                  <RegisterLink className="btn btn-dark">Sign up</RegisterLink>
                </>
              ) : (
                <div className="profile-blob">
                  {user?.picture ? (
                    <img
                      className="avatar"
                      src={user?.picture}
                      alt="user profile avatar"
                      referrerPolicy="no-referrer"
                    />
                  ) : (
                    <div className="avatar">
                      {user?.given_name?.[0]}
                      {user?.family_name?.[0]}
                    </div>
                  )}
                  <div>
                    <p className="text-heading-2">
                      {user?.given_name} {user?.family_name}
                    </p>

                    <LogoutLink className="text-subtle">Log out</LogoutLink>
                  </div>
                </div>
              )}
            </div>
          </nav>
        </header>
        <main>{children}</main>
      </body>
    </html>
  );
}
```

getUser - it will collect informations such as Profile Image on Google, and your name

isAuthenticated - check if the user signed up and signed in.

Thank you for reading this quickKinde and NextJS guide, I hope I could help you. Follow me for more. (part 2 is coming with more possibilities of Kinde)

Take care :)

## Checkout our new design [click here](https://www.whiz.hu/)!