Integrating Authentication using Clerk to your     NextJS Project.

Integrating Authentication using Clerk to your NextJS Project.

·

5 min read

While creating any web application with your favourite tech stack, you might have come up with the term "Authentication". You would have started looking at integrating it into your project to make it more user-friendly.

In this article, we will discuss one service that lets you integrate authentication in your project, Clerk and how we can use it with our NextJS project. Before diving deeper into Clerk, let's review some terminologies and why we use them.

What is authentication?

No matter the size and scope of your web application, a great developer will always think about keeping the user data protected so that users have the best experience while using the application. This is where authentication comes into play.

Not to get confused, we should understand the difference between "Authentication" and "Authorisation".

With Authentication, you are trying to identify the user with credentials you have received, while Authorization determines whether this identified user should have access to a particular resource.

There are many ways to implement authentication, to name a few: you can use API Keys, tokens, OAuth OpenID connect, etc.

One such way to implement authentication to your project is Clerk.

Let's dive straight into Clerk to explore it's power.

What is Clerk?

Clerk is a cloud-based authentication service that aims to simplify the integration of secure authentication in web applications. It allows developers to concentrate on developing the core features of their application without worrying about the complicated aspect of authentication. With Clerk, you can:

  • Permit users to log in using their Google, GitHub, or other social network accounts that they already have.

  • Allow users to log in using a one-time passcode (OTP) given to their phone instead of a password.

  • From a single dashboard, control user accounts, roles, and permissions.

  • You can protect your app using built-in Clerk features like session management and password protection.

Setting up Clerk in your NextJS project.

Clerk helps in adding secure authentication and user management to your Next.js application in a smooth way.

Once you have your Next.js app ready, the steps that are needed to be followed are:

Step 1) Install Clerk's Next.js SDK using npm. Type the following command in the directory of your Next.js project:

npm install @clerk/nextjs

Step 2) Once Clerk is installed, we must have the API key to our project. For that, you need to create a .env.local file in the project's root directory. The contents of the .env.local file should be as follows:

NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_<YOUR_PUBLISHABLE_KEY>
CLERK_SECRET_KEY=sk_test_<SECRET_KEY>

To get your Publishable and the Secret Key, you must create an account on Clerk and an application. After creating an account, visit the Clerk dashboard, click on Add application and give the application a name. Once your application is created on Clerk, you can access the keys from the User Dashboard.

Step 3) After installing Clerk, we can make it accessible to all your pages by adding its provider to our Next.js application. To accomplish this, import the ClerkProvider component from the clerk package and add it to the layout.tsx file for your application. The <ClerkProvider> component will provide active session and user context to Clerk’s hooks and UI components.

// layout.tsx

import { ClerkProvider } from '@clerk/nextjs'

export const metadata = {
  title: 'Next.js 13 with Clerk',
}

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

Now that the ClerkProvider component has been added; we can use Clerk’s authentication features.

Step 4) Now that Clerk is installed and mounted in your application, it’s time to decide which pages are public and which need to hide behind authentication. We do this by creating a middleware.ts file in the root folder (or inside src/ if that is how you set up your app).

// middleware.ts

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

// This example protects all routes including api/trpc routes
// Please edit this to allow other routes to be public as needed.
// See https://clerk.com/docs/references/nextjs/auth-middleware for 
// more information about configuring your middleware
export default authMiddleware({});

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

With this middleware, your entire application is protected. If you try to access it, the middleware will redirect you to your Sign Up page.

Step 5) In addition to the Account Portal, Clerk also offers a set of prebuilt components that you can use instead to embed sign-in, sign-up, and other user management functions into your Next.js application. We are going to use the <SignIn /> and <SignUp /> components by utilizing the Next.js optional catch-all route.

// Sign-Up Page

// app/sign-up/[[...sign-up]]/page.tsx

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

export default function Page() {
  return <SignUp />;
}
// Sign-In Page

// app/sign-in/[[...sign-in]]/page.tsx

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

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

Next, add environment variables for the signIn, signUp, afterSignUp, and afterSignIn paths:

// .env.local

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=/

These values control the behaviour of the components when you sign in or sign up and when you click on the respective links at the bottom of each component.

Step 6) The <UserButton /> allows users to manage their account information and log out, thus allowing you to complete a full authentication circle.

You can add it anywhere, but next to the logo on your main application page is a good start.

// app/page.tsx

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

export default function Home() {
  return (
    <div>
      <UserButton afterSignOutUrl="/"/>
    </div>
  )
}

Step 7) Now start your Next.js application via npm run dev, visit http://localhost:3000, and sign up to get access to your application.

With this, the Clerk SDK will automatically handle the authentication flow and interactions with the social providers. When a user clicks on a certain provider’s social login button (e.g., “Sign in with Google”), your application should call the Clerk SDK to begin the social login sequence. The Clerk SDK will redirect users to the social provider’s login page, where they can enter their credentials or validate the authentication procedure.

Conclusion

In this article, we discussed how Clerk handles user authentication in Next.js, offering secure sign-up and sign-in functionality securely and easily.

Clerk is a robust authentication module that offers many advantages to Next.js apps, like ease of use, security and flexibility.

I hope you have enjoyed this blog and found a new, interesting, and powerful way to add user authentication to your Next.js projects.

Happy Learning and Coding!

References:

https://clerk.com/docs/quickstarts/nextjs

https://nextjs.org/docs/getting-started/installation