DEV Community

Aayush Kumar bhat
Aayush Kumar bhat

Posted on

How to integrate Clerk in Next JS application ?

Hello everyone, in this aritcle you will go through the simple process of using Clerk in your Next JS application.

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

Clerk is nothing but a 3rd party authentication service. Clerk authentication 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 
Enter fullscreen mode Exit fullscreen mode

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

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


STEP 2: Creating an Account in Clerk!
Visit to THIS link and create a new account.

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

Image description

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


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


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


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
Enter fullscreen mode Exit fullscreen mode

Image description


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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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>
  )
}

Enter fullscreen mode Exit fullscreen mode

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)(.*)"],
};


Enter fullscreen mode Exit fullscreen mode

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 />;
}
Enter fullscreen mode Exit fullscreen mode

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

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

export default function Page() {
      return <SignUp />;
}
Enter fullscreen mode Exit fullscreen mode

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

Image description


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=/
Enter fullscreen mode Exit fullscreen mode

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

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.

Enter fullscreen mode Exit fullscreen mode

FINAL RESULT

Image description

Image description

Top comments (1)

Collapse
 
amandeepkaur profile image
Amandeep kaur

Great!