DEV Community

Cover image for Next JS Authentication With Clerk
Mansour Mahamat
Mansour Mahamat

Posted on • Originally published at avocadogrowth.com

Next JS Authentication With Clerk

We will walk you through using Clerk and Next.js to establish authentication in your online apps in this step-by-step guide. Clerk offers a streamlined development experience as well as strong user security. You can quickly construct safe and user-friendly authentication systems when you combine it with the adaptability and efficiency of Next.js.

You can do the following using Clerk:

  • Allow people to check in using their existing Google, GitHub, or other social network accounts.
  • Allow users to log in without a password by utilizing a one-time passcode (OTP) sent to their phone.
  • Control user accounts, responsibilities, and permissions from just one dashboard.
  • Using built-in Clerk features like session management and password security, you can secure your app.

Setting Up Your Next.js Application

First, let's create a new Next.js project by running the following commands in your terminal:

npx create-next-app my-clerk-app
cd my-clerk-app

Enter fullscreen mode Exit fullscreen mode

First step is to create a Clerk account. You can do this by visiting clerk.dev and signing up for a free account.

Image description

After logging in, click the Add application button. Give your app a name and pick all of the 'Social authentication' options you want your users to utilize.

coding

Installing Clerk in the Next.js Application

We must add our API key to our project after installing Clerk.
This may be accomplished by placing a.env.local file in the root directory of your Next.js project. The following settings should be included in the.env.local file:

NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=<your clerk public key>
CLERK_SECRET_KEY=<your clerk secret key>
Enter fullscreen mode Exit fullscreen mode

To get our Clerk’s public and secret keys, it's on Clerk dashboard

coding

Navigate to your Next.js project's directory and run the following command to install Clerk :

yarn add @clerk/nextjs
Enter fullscreen mode Exit fullscreen mode

Adding Clerk’s authentication provider

// app/layout.jsx
import { ClerkProvider } from "@clerk/nextjs"

const Layout = ({ children }) => {
  return (
    <ClerkProvider>
      <html lang="en">
        <body className={inter.className}>{children}</body>
      </html>
    </ClerkProvider>
  )
}

export default Layout
Enter fullscreen mode Exit fullscreen mode

Protecting your Application Routes

Once you've integrated Clerk into your application, the next step is to determine which pages should be accessible to the public and which ones should require user authentication. This is achieved by creating a middleware.js file at the project's root and specifying which routes are public and which are private. In our specific scenario, we want only the home page to be accessible to the public, while the other pages should remain hidden until the user logs in to the application. You can accomplish this by implementing the following code:

// Protects access from all the other pages except the home page

import { authMiddleware } from "@clerk/nextjs"

export default authMiddleware({
  publicRoutes: ["/"],
})

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

User Registration and Login

Clerk offers a range of pre-built components that simplify the integration of sign-in, sign-up, and other user management capabilities into your Next.js application.

To implement this, navigate to the "app" folder of your project and create two new directories named "sign-up" and "sign-in". Within each of these directories, you should insert the respective code for the sign-up and sign-in functionalities.

Signin

// app/sign-in/pages.js

import { SignIn } from "@clerk/nextjs"

const signIn = () => {
  return (
    <div>
      <SignIn />
    </div>
  )
}

export default signIn
Enter fullscreen mode Exit fullscreen mode

Signup

// app/sign-in/pages.js

// app/sign-up/pages.js

import { SignUp } from "@clerk/nextjs"

const signUp = () => {
  return (
    <div>
      <SignUp />
    </div>
  )
}

export default signUp
Enter fullscreen mode Exit fullscreen mode

To access Clerk's login page at http://localhost:3000/sign-in, make sure you have set up your Next.js application properly with Clerk and that the routes are configured correctly.

Ensure the following steps:

  • Verify that Clerk has been integrated into your Next.js application.

  • Make sure you have a route or page set up for /sign-in in your Next.js application.

  • Confirm that Clerk's login components are correctly imported and rendered on the /sign-in page.

If all these steps have been completed successfully, visiting http://localhost:3000/sign-in in your web browser should load Clerk's login page as intended.

local

SignedOut and User Profile

Clerk provides a collection of purpose-specific components, including "SignedIn," "SignedOut," and "RedirectToSignIn," designed to simplify user authentication management within our application.

These components allow us to easily integrate authentication functionality into other components.

With them, we can dynamically control our application's behavior based on the user's sign-in status. Additionally, we have the flexibility to trigger redirection to the sign-in page when necessary. These components significantly enhance our ability to seamlessly manage user authentication in our application.

Create a new component called Navbar :

//  components/navbar.jsx
const Navbar = () => {
  return (
    <nav>
      <SignedIn>
        <UserButton />
      </SignedIn>
      <SignedOut>
        <SignInButton mode="modal">
          <button className="rounded border border-gray-400 px-3 py-0.5">
            Sign in
          </button>
        </SignInButton>
      </SignedOut>
    </nav>
  )
}

export default Navbar
Enter fullscreen mode Exit fullscreen mode

Update your app/layout.jsx :

<ClerkProvider>
  <html lang="en">
    <body className={inter.className}>
      <Navbar />
      {children}
    </body>
  </html>
</ClerkProvider>
Enter fullscreen mode Exit fullscreen mode

Not in your app folder create a new page called protected you should not be able to access if you're not logged :

// app/protected/page.jsx
import React from "react"

function page() {
  return <div>protected</div>
}

export default page
Enter fullscreen mode Exit fullscreen mode

In this article, we discussed how Clerk simplifies authentication in Next.js, offering secure sign-in, sign-up, and sign-out. We explored how to handle authentication events and protect our routes.

You should now have a fully authenticated application as highlighted below :

Clerk is a robust authentication module that offers many advantages to Next.js apps. These advantages consist of:

  • Ease of use: Clerk integrates well with Next.js applications and is simple to use.
  • Security: Clerk is an authenticating library that adheres to accepted security standards.
  • Flexibility: Clerk may be tailored to match the unique requirements of your application since it is adaptable. I recommend checking out Clerk if you’re looking for a user-friendly, reliable, and adaptable authentication library for your Next.js application. You can get further details on Clerk’s website for documentation and resources. Here’s the link to the finished project on Github

ORIGINAL POST

ORIGINAL POST

Top comments (0)