Authentication with Clerk in Next.js
Adding authentication to a Next.js application used to mean choosing between building it yourself (weeks of work, endless security footguns) or integrating a complex auth library. Clerk simplifies this to a few lines of code while handling the hard parts: multi-factor authentication, social logins, session management, and user profiles.
Initial Setup
Install @clerk/nextjs and create a Clerk application at clerk.com. Add your NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY to .env.local. Wrap your root layout with ClerkProvider. That is it for the basic setup — Clerk is now available throughout your application.
Adding Sign-In and Sign-Up
Clerk provides prebuilt components: SignIn, SignUp, and UserButton. Create a sign-in page at app/sign-in/[[...sign-in]]/page.tsx and render the SignIn component. Same for sign-up. Customize the appearance with Clerk theming API to match your application design. The components handle email/password, social OAuth, magic links, and phone number authentication out of the box.
Protecting Routes with Middleware
Create a middleware.ts file that uses clerkMiddleware to protect routes. Define public routes (landing page, pricing, docs) and protected routes (dashboard, settings, API). The middleware redirects unauthenticated users to the sign-in page and handles session token refresh automatically.
Server-Side Authentication
In Server Components, use auth() to get the current user session. In API routes, use the same auth() function. Clerk handles JWT verification, session validation, and token refresh. Access user metadata with currentUser() for profile information like name, email, and avatar.
Webhooks and User Sync
Sync Clerk users to your database using webhooks. When a user signs up, Clerk sends a user.created webhook to your API. Parse the event, create a user record in your database with the Clerk user ID as a foreign key, and set default preferences. Handle user.updated and user.deleted events to keep your database in sync.
Related Posts
Sponsor Our Newsletter
Reach thousands of developers who are actively evaluating AI tools, MCP servers, and dev infrastructure. Our weekly newsletter goes to engaged technical decision-makers.
All sponsored content is clearly labeled per our editorial policy.