Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Atsushi Miyamoto
Atsushi Miyamoto

Posted on

     

Implementing Authentication with Clerk in Next.js

Introduction

Hello! I'm Atsushi, a cloud engineer working at a SaaS company in Tokyo. Recently, I implemented authentication features for my personal AI chatbot project using Clerk, an authentication service. I'd like to share the insights I gained from this experience.

What is Clerk?

Clerk is a service that provides embeddable UI components, APIs, and an administrative dashboard for user authentication and management. It supports frontend frameworks like Next.js, React, and Remix.

In addition to authentication features, Clerk offers UI components that make it easy to implement sign-in and login screens. It also integrates with services like Supabase and Firebase.

Account Creation

To get started with Clerk:

  1. Sign up atClerk's website by clicking the "Get started" button.
  2. After creating an account, set up your application by providing a name and clicking "Create application".

Implementing Authentication Screens

Clerk provides UI components that make it easy to implement authentication screens. This guide focuses on implementation with Next.js using the App Router.

Prerequisites

  1. Set environment variables in.env.local:
   NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=xxx   CLERK_SECRET_KEY=xxx
Enter fullscreen modeExit fullscreen mode
  1. Set up the Clerk Provider inapp/layout.tsx:
import{ClerkProvider}from'@clerk/nextjs'import{jaJP}from'@clerk/localizations'exportdefaultfunctionRootLayout({children,}:{children:React.ReactNode}){return(<ClerkProviderlocalization={jaJP}><html><body><main>{children}</main></body></html></ClerkProvider>)}
Enter fullscreen modeExit fullscreen mode
  1. Implement Middleware inmiddleware.ts:
import{clerkMiddleware}from'@clerk/nextjs/server'exportdefaultclerkMiddleware()exportconstconfig={matcher:['/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)','/(api|trpc)(.*)',],}
Enter fullscreen modeExit fullscreen mode

Using Standard Components

Clerk provides ready-to-use components like<SignUp /> and<SignIn /> that can be easily implemented:

import{SignUp}from'@clerk/nextjs'exportdefaultfunctionPage(){return<SignUp/>}
Enter fullscreen modeExit fullscreen mode

Custom Implementation with React Hook Form

For more control over the form, you can use React Hook Form with Clerk's helpers:

  1. Create a custom hook (useSignInForm):
import{useSignIn}from'@clerk/nextjs'import{zodResolver}from'@hookform/resolvers/zod'import{useForm}from'react-hook-form'import{z}from'zod'// ... (schema and type definitions)exportconstuseSignInForm=()=>{const{isLoaded,setActive,signIn}=useSignIn()// ... (form setup and submit handler)}
Enter fullscreen modeExit fullscreen mode
  1. Create a Form Provider:
import{useSignInForm}from'@/hooks/sign-in/use-sign-in'import{FormProvider}from'react-hook-form'constSignInFormProvider=({children}:Props)=>{const{methods,onHandleSubmit,loading}=useSignInForm()return(<FormProvider{...methods}><formonSubmit={onHandleSubmit}>{children}</form></FormProvider>)}
Enter fullscreen modeExit fullscreen mode
  1. Create the Form component:
import{useFormContext}from'react-hook-form'constLoginForm=()=>{const{register,formState:{errors},}=useFormContext()return(<><h2>Login</h2><input{...register('email')}/><input{...register('password')}/></>)}
Enter fullscreen modeExit fullscreen mode
  1. Implement the login page:
importSignInFormProviderfrom'@/components/forms/sign-in/form-provider'importLoginFormfrom'@/components/forms/sign-in/login-form'constSignInPage=()=>{return(<SignInFormProvider><LoginForm/><buttontype="submit">Login</button></SignInFormProvider>)}
Enter fullscreen modeExit fullscreen mode

Retrieving Authentication Information

To get the user ID after sign-up:

import{currentUser}from'@clerk/nextjs/server'constuser=awaitcurrentUser()constid=user.id
Enter fullscreen modeExit fullscreen mode

Conclusion

Clerk significantly simplifies the implementation of authentication features.
Its flexibility allows for easy integration with popular tools like React Hook Form and Zod.
However, for Next.js projects, alternatives like Auth.js or Supabase's built-in authentication should also be considered depending on the use case.

References

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I’m a Software Engineer who loves building applications—having working experience of more than 3 years. I love new technology and have the curiosity to learn new things! Life-long learner.
  • Location
    Japan
  • Education
    University of the People
  • Work
    Cloud Engineer
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp