How to integrate Clerk in Next JS application ?
Aayush Kumar bhat
Posted on August 22, 2023
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.
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
Clerk offers more than 19 methods for authentication.
Some of them are:
- GitHub
- Apple
- Mircosoft and so on... Give a name to the application and select the required methods. Click on CREATE APPLICATION
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.
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.
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
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:
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
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
Posted on August 22, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.