DEV Community

Cover image for Auth with Clerk
Njabulo Majozi
Njabulo Majozi

Posted on • Edited on • Originally published at njabulomajozi.com

Auth with Clerk

It can be challenging to set up user authentication for web apps. Creating login flows, safely hashing passwords, controlling sessions, and integrating social logins are all part of the traditional process, guaranteeing optimal security. Luckily, there's a more effective method.

In a recent project, I investigated Clerk, a powerful solution for simplifying user authentication in Next.js applications. Let's explore why Clerk has become my preferred option and how it streamlines development.

Why Clerk Auth?

Forget about the time-consuming back-end configurations. With a wide range of capabilities aimed at improving the security and usability of your application, Clerk gives you the power to:

  • Embeddable UIs: Say goodbye to custom login forms! Clerk provides pre-built UI components like SignIn, SignUp, UserButton, and UserProfile that seamlessly integrate into your Next.js and other frontend frameworks supported by Clerk.
  • Authentication: Clerk offers a comprehensive set of authentication options, including:
    • Multifactor Authentication (MFA): Add an extra layer of security with MFA to protect user accounts.
    • Session Management: Includes maximum lifetime, inactivity timeout, and multi-session apps.
    • Social Sign-On: Make logging into well-known social media sites like Google, Microsoft, and others easier.
    • Email/SMS One-Time Passcodes (OTPs): Send verification codes via email or SMS to offer easy log-in.
    • Magic Links: Simplify the login procedure by using links that, when clicked, provide access.
  • Flexibility: Integrate Clerk seamlessly with your preferred development stack:
    • Frontend SDKs: Integrate Clerk with popular frontend frameworks like Next.js, React, React Native/Expo, and more.
    • Backend SDKs: Leverage Clerk's backend SDKs for Node.js, Go, and other languages.
  • More
    • Admin Dashboard: Manage user authentication and access control from a centralized, secure dashboard.
    • Integrations: Expand your application's functionality by integrating Clerk with other services, such as Firebase, Supabase, and more.
    • Webhooks: Stay informed about user activities through real-time notifications.
    • Bot Detection: Clerk helps mitigate brute-force attacks with built-in bot detection mechanisms.
    • B2B Suite: Build secure and scalable authentication experiences for your business-to-business applications.

Setting Up Clerk Auth in Next.js

  • Install Clerk

    npm install @clerk/nextjs
    
  • Configure Clerk

    By adding the following environments in .env.local

    NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=<your clerk public key>
    CLERK_SECRET_KEY=<your clerk secret key>
    
  • ClerkProvider

    Provide authentication context to the rest of the application by wrapping around an app, such as root layout.tsx

    ...
    import { ClerkProvider } from '@clerk/nextjs';
    
    ...
    
    export default function RootLayout({
      children,
    }: {
      children: React.ReactNode;
    }): JSX.Element {
      return (
        <ClerkProvider>
          <html lang="en">
            <body>{children}</body>
          </html>
        </ClerkProvider>
      );
    }
    
  • Middleware

    Clerk's middleware functionality in the Next.js middleware file handles authentication, protects routes, and ensures that only authenticated users can access them.

    import { authMiddleware } from "@clerk/nextjs";
    
    export default authMiddleware({});
    
    export const config = {
      matcher: [ 
        "/((?!.+\\.[\\w]+$|_next).*)",
        "/(api|trpc)(.*)"
      ]
    };
    
  • Configure type of auth strategy through a dashboard

    Clerk supports authentication strategies such as password login, social authentication (allowing users to log in using their Google, GitHub, or other social network accounts. This feature enhances the user experience by providing a familiar login process), and more. To those auth strategies, you need to configure it in your Clerk dashboard.

Additionally, Clerk supports various authentication strategies, such as password login and social authentication, which can be configured seamlessly through the Clerk dashboard.

My journey with Clerk Auth has been nothing short of transformative. It's revolutionized how I approach user authentication, offering unparalleled simplicity without compromising security. Clerk isn't just a tool – it's a game-changer for Next.js development.

Top comments (0)