Next.js + Clerk Authentication
Add complete authentication with user management, social logins, and protected routes using Clerk.
Create Next.js Project
Bootstrap a new Next.js app with TypeScript and the App Router.
npx create-next-app@latest my-app --typescript --tailwind --app --src-dirInstall Clerk SDK
Install the official Clerk Next.js SDK.
npm install @clerk/nextjsGet Clerk API Keys
Create a new application at dashboard.clerk.com. Copy the NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY from the API Keys section.
Wrap App with ClerkProvider
Add ClerkProvider to your root layout. This makes auth state available throughout your app. See ClerkProvider docs.
Add Auth Middleware
Create src/middleware.ts to protect routes. The clerkMiddleware helper integrates with Next.js middleware to redirect unauthenticated users. See auth middleware docs.
Create Sign-In and Sign-Up Pages
Add Clerk's pre-built auth UI components. Place them in the correct directories so Clerk's redirect variables work automatically.
Build a Protected Dashboard
Use currentUser() on the server or useUser() on the client to access user data. Both are provided by the Clerk SDK.
Add Navigation with Auth State
Use Clerk's <SignedIn>, <SignedOut>, and <UserButton> components to build a header that adapts to auth state.
Protect API Routes
Use auth() in Route Handlers to secure API endpoints. Returns userId: null for unauthenticated requests.
Start Development Server
Run the dev server and navigate to / to see the public page, then try /dashboard to trigger the auth redirect.
npm run devFound this guide helpful? Check out more tools and guides.
Browse All GuidesPrerequisites
- Node.js 18+
- Clerk account (free tier available)