Next JS Authentication With Clerk
Tags: javascript, tutorial, nextjs
Published: 2023-11-01 13:46:29

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:

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

```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02rkzw8efvazmhamz8sx.png)

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](https://res.cloudinary.com/mansdesmez/image/upload/v1698609654/Capture_d_e%CC%81cran_2023-10-29_a%CC%80_21.00.38_qictgv.png)

# 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:

```bash
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=<your clerk public key>
CLERK_SECRET_KEY=<your clerk secret key>
```

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

![coding](https://res.cloudinary.com/mansdesmez/image/upload/v1698609908/Capture_d_e%CC%81cran_2023-10-29_a%CC%80_21.04.54_vyvasj.png)


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

```bash
yarn add @clerk/nextjs
```

# Adding Clerk’s authentication provider

```javascript
// 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
```

# 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:

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

# 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

```javascript
// app/sign-in/pages.js

import { SignIn } from "@clerk/nextjs"

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

export default signIn
```

## Signup

```javascript
// app/sign-in/pages.js

// app/sign-up/pages.js

import { SignUp } from "@clerk/nextjs"

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

export default signUp
```

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](https://res.cloudinary.com/mansdesmez/image/upload/v1698611072/Capture_d_e%CC%81cran_2023-10-29_a%CC%80_21.24.19_uicndd.png)

# 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 :

```javascript
//  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
```

Update your app/layout.jsx :

```javascript
<ClerkProvider>
  <html lang="en">
    <body className={inter.className}>
      <Navbar />
      {children}
    </body>
  </html>
</ClerkProvider>
```

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

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

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

export default page
```

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](https://avocadogrowth.com/en/blog/tutorials/auth-with-clerk-nextjs)

[ORIGINAL POST](https://avocadogrowth.com/en/blog/tutorials/auth-with-clerk-nextjs)