How to integrate Clerk in Next JS application ?
Tags: webdev, tutorial, javascript, nextjs
Published: 2023-08-22 16:28:54

Hello everyone, in this article you will go through the simple process of integrating **Clerk** as 3rd party user authentication in your **Next JS** application. 


Note: For the learning purpose, If you haven't build any authentication from scratch, first learn the basics of working of user authentication and build atleast one or two authentication pages.  


**Clerk** is nothing but a 3rd party authentication service. Clerk is a secure way to control access to digital platforms or apps. It ensures that only authorized users can use these services. Think of it like a virtual bouncer at a club entrance – it checks IDs (login credentials) to verify who's allowed in. Clerk authentication uses techniques like passwords, biometrics (like fingerprints), and single sign-on to confirm a user's identity. This prevents unauthorized access and safeguards sensitive information. Just like a lock and key, Clerk authentication keeps digital spaces safe from unwanted visitors while letting the right people enjoy the benefits.


                             ## LET'S START 

---

**STEP 1**: **Creating Next JS application!**

Using the command `npx create-next-app ./folderName`, generate a basic Next JS application and folder structure. Make sure that you enter the same as I did. 



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

Once the folder structure is generated, we can move to the next step.


---

**STEP 2**: **Creating an Account in Clerk!**
Visit to [THIS](https://dashboard.clerk.com/sign-up) link and create a new account.

Now it will redirect you to the Application page which would look like this


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

Clerk offers more than 19 methods for authentication.
Some of them are:
1. Google 
2. Facebook 
3. GitHub
4. Apple 
5. LinkedIn 
6. Mircosoft
and so on...
Give a name to the application and select the required methods.
Click on **CREATE APPLICATION**


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

---

**STEP 3**: **SELECTION OF FRAMEWORK TO BE USED**
This tutorial is for Next JS, so I will be selecting Next.js only.
Otherwise it offers 5+ frameworks.

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

---

**STEP 4**: **CREATING .env file**

Now in the root folder of your project create a .env file then add **CLERK_SECRET_KEY** and **NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY** 
These keys would be different in your case, so make sure that you add yours only.

**Note**: Remeber to add the .env file in the .gitignore file. 


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

---

**STEP 5**: **INSTALLING CLERK**

Install clerk in your project depending on the framework you have choosed.
In this case, we are going Next, if you are using the same make sure you enter the same.

```
npm install @clerk/nextjs
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ymfiz63i236p9sh5fys.png)

---

**STEP 6**: **MOUNTING THE CLERK**
For mounting the clerk on entire application we need to import ClerkProvider and wrap it around our main app. 

Go to ./"ProjectName"/app/layout.tsx

layout.tsx 

**Initially**

```
import './globals.css'
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'

const inter = Inter({ subsets: ['latin'] })

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>{children}</body>
    </html>
  )
}
```

After wrapping the application with ClerkProvider.
We need to import the **ClerkProvider ** from @/clerk/nextjs as a named import. 

```

import { ClerkProvider } from '@clerk/nextjs'
import './globals.css'
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'

const inter = Inter({ subsets: ['latin'] })

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <ClerkProvider>
      <html lang="en">
        <body className={inter.className}>{children}</body>
      </html>
    </ClerkProvider>
  )
}

```
---

**STEP 7**: **ADDING MIDDLEWARE**

For the protection of our project or application while authentication, we need to a middleware.

Create a file in the root directory of your project as **middleware.ts** copy and paste the follwiing code. 

```

import { authMiddleware } from "@clerk/nextjs";

export default authMiddleware({});

export const config = {
  matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};


```
---

**STEP 8**: **ADDING SIGNUP AND LOGIN PAGES**
**PAY ATTENTION **

Clerk requires a parituclar folder structure.

i. Create 2 folders named as "(auth)" and "(root)".

ii. Inside (root), create a new file as page.tsx. This file is the main file of the application.

iii. Inside (auth), create another folder named as "(routes)".
 
iv. Inside (routes) create 2 more folder as "sign-in"and "sign-up".

v. Inside sign-in and sign-up create new folders named as [[...sign-in]] and [[...sign-up]] respectively.

vi. Create files both named as page.tsx in sign-in and sign-up.

Now copy the code respectively.

For page.tsx in [[...sign-in]]:

```
import { SignIn } from "@clerk/nextjs";

export default function Page() {
      return <SignIn />;
}
```

For page.tsx in [[...sign-up]]:

```
import { SignUp } from "@clerk/nextjs";

export default function Page() {
      return <SignUp />;
}
```

In the end, your folder structure for auth should look like this:



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

---

**STEP 9**: "ADDING ENVIRONMENT VARIABLES IN .env file"

```
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/
```

CONGRATS!!! **YOU HAVE SUCCESSFULLY INTEGRATED CLERK WITH YOUR APPLICATION **


!(https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0d0cuhw17zmd2nyzc2nv.png)

In order to center the login/signup modal or box, we need to add the layout for auth too. 

*Each route group can have its own layout.


For adding a layout, you can do the following: 

i. Create a file named as layout.tsx. Empty file will make next.js thrown an error, since next expects a layout file to return a function.

**Error**

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



Copy the code:

```
export default function AuthLayout({
      children
}: {
      children: React.ReactNode
}) {
      return (
            <div className="flex items-center justify-center h-full">{children}</div>
      )
}
// this file is responsible for the layout of entire auth page.

```

## **FINAL RESULT**


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


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