DEV Community

Cover image for Authentication is that easy
Timi
Timi

Posted on

Authentication is that easy

Authentication is a crucial part of any web application, without authentication anyone of any kind can have access to files, pages, or other items they don't need to have access to, and it's important to get this thing we call authentication right.

There are so many Authentication platforms or providers as you may call them. Clerk has always been my favorite. Now I'm not usually the one to pick favorites but I've used other providers or platforms, test run them, and use them in production. But there is something I love about Clerk which I will dive into in a moment.

Why did I choose Clerk?

What made me fall in love with Clerk is their easy-to-read documentation. I have never seen something very easy to read and understand like this before. The fact that they even support both the app/ dir and the pages/ dir makes it top-notch.

Other Alternatives

Yes, Clerk is amazing, but there are so many other great alternatives out there. Now you may not like Clerk, but I believe with every platform comes different alternatives to build on top of.

Here are other clerk alternatives you could try

Platform Type Description
Okta Cloud-based A cloud-based identity management platform that provides single sign-on, multi-factor authentication, and user provisioning.
Auth0 Cloud-based A cloud-based identity and access management platform that provides authentication, single sign-on, and authorization services.
Amazon Cognito Cloud-based A cloud-based identity management service that provides user registration, authentication, and authorization.
Microsoft Azure Active Directory Cloud-based A cloud-based identity and access management service that provides single sign-on, multi-factor authentication, and user provisioning.
Firebase Authentication Cloud-based A cloud-based authentication service that provides user registration, authentication, and authorization.
Supabase Cloud-based An open-source, Firebase alternative that provides a complete backend platform, including authentication, database, storage, and more.
Authlogic Self-hosted A self-hosted authentication library for Ruby on Rails.
Devise Self-hosted A self-hosted authentication library for Ruby on Rails.
Clearance Self-hosted A self-hosted authentication library for Python.
Warden Self-hosted A self-hosted authentication library for Ruby on Rails.
Passport Self-hosted A self-hosted authentication library for Node.js.

Now there are so many other alternatives, but one of these should look familiar to you.

Setting up Clerk for Authentication

Now we would look at how to set up Clerk on your Nextjs app.

Prerequisites

  • A Next.js app
  • A Clerk account

Steps:

1. Install the @clerk/nextjs package.

npm install @clerk/nextjs
Enter fullscreen mode Exit fullscreen mode

2. Set up your environment keys.

In your Nextjs project's root folder, you need to create a .env.local file. This is where all your secrets would go.

NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_Z3JlYXQtdGlnZXItOTYuY2xlcmsuYWNjb3VudHMuZGV2JA
CLERK_SECRET_KEY=sk_test_HIqOePkGpnR6QyWVLn3LUsqCsoD1MHEieVdiZXsei2
Enter fullscreen mode Exit fullscreen mode

3. Wrap your app in <ClerkProvider />

Now you are done adding your environment variables, let's talk about the <ClerkProvider /> component. This component is important because it makes the Clerk context available to your entire app. First, we would need to import it and then use it.

App Router: The app/layout.tsx file might be in your src folder if it isn't in your root folder.

import { ClerkProvider } from '@clerk/nextjs'

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

      </html>
    </ClerkProvider>
  )
}
Enter fullscreen mode Exit fullscreen mode

We are simply importing the component and mounting it to the RootLayout. This takes control over every element in your Next app, which means even if you route to another page aside from the homepage, the Auth workflow will still take place.

4. Protecting your app

Now a true authenticated app has lots of protection underneath the hood. In this step, we will cover the requirement of authentication to access this application.

Now previously we installed Clerk and mounted it to our application. This time we decide which page can be public to the user and which pages are protected. To do so we would need to create a middleware.ts file. Note you need to be on the app router for this to work properly.


Create a middleware.ts file in the root directory of your app.

Now clerk gave us a wonderful template to use, this template protects our application from every route you create. To add this protection simply copy and paste the following code into your 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)(.*)'],
};
Enter fullscreen mode Exit fullscreen mode

Now this code is responsible for protecting all routes, including API and TRPC routes, from unauthorized access.

Broad Explantation

The authMiddleware function from @clerk/nextjs is a pre-configured middleware that authenticates users using Clerk. It takes an options object as a parameter, which can be used to customize its behavior.

The matcher option in the config object specifies the routes that the middleware should protect. In this case, the middleware will protect all routes, including API and TRPC routes.


5. Building your sign-in and sign-up page

What's an authentication without the sign-in and sign-up page, I mean how else are your users able to access your application?

Build your sign-up page

To build the sign-up page in Clerk, we would need a special component, remember when we installed Clerk? Now this package came with a bunch of interesting components we can use. One of them is our own sign-in and sign-up page

To get started we need to create a new file, this file would be used to render the sign-up page. Think of it like you exporting your Component, with a bunch of functions inside it. Now when Importing that component we also import its functions. This is why It's so interesting.

If you are using the app/ router the file should look like this:

app/sign-up/[[...sign-up]]/page.tsx
Enter fullscreen mode Exit fullscreen mode

So in brief we created two folders, the sign-up and [[...sign-up]]

Now remember in the nextjs app/ router to create a route named /dog. we would do something like this

dog/page.tsx
Enter fullscreen mode Exit fullscreen mode

The dog is a folder, and the page.tsx is the file.

Now after you have successfully created the two folders with the file for routing, you need to paste the following code.

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

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

Build your sign-in page

Now the only thing we should change here is the folder names, so now it should be sign-in and [[...sign-in]]. After that, you can now copy the following code.

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

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

6. Updating your environment variables

You might assume that the authentication process is complete and that your routes are functional, but unfortunately, that's not the case. In order for both of these aspects to function properly, we need to make a small adjustment to our environment variables.

Now we should add environment variables for the signIn, signUp, afterSignUp, and afterSignIn paths:

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

Now let me explain. Remember the routes for sign-in and sign-up that we created. Well, we just created it, for Clerk to be able to know which route is our signIn and signUp path we need to specify it.

We are just basically saying where our route should go for sign-in and signup, and then where it should go after It's finishing signing in and signing up the user.


Now with these, you have successfully provided Authentication to our Nextjs app. Go build great stuff 🎉

Top comments (0)