How to Use Clerk: The Beginner's Guide (First App, Sign-In That Works, Protected Pages, and the Keys You Never Commit)

CodexFuse Team · 2026-10-31T03:57:27.257Z · 11 min read

Learn how to use Clerk: create your first app, add the SDK, add sign-in with prebuilt components, protect your routes, and guard your secret key.

Learning how to use Clerk is one of the fastest ways to give your first real app proper sign-in without building an auth system from scratch. Clerk is a hosted authentication service: it handles user accounts, sign-in screens, sessions, password security, and social logins, while your app talks to it through an SDK. The beginner path is short: create a free Clerk app, run one CLI command that wires up the SDK, provider, and keys, drop in prebuilt sign-in and sign-up components, add middleware so signed-out visitors cannot open protected pages, and read the signed-in user on the server. If you need a strong password for your very first test account, generate one with a password generator instead of reusing something memorable — your auth setup is only as strong as the credentials you test it with.

How Do You Use Clerk? (The 5-Minute Answer)

The fastest way to answer "how to use Clerk" for a beginner is the official CLI: npx -y clerk@latest init installs the SDK, writes your keys to .env.local, wraps your app in the auth provider, and creates the middleware file. Before that you create a free app in the Clerk Dashboard; after the CLI finishes, you add prebuilt sign-in and sign-up components and one middleware rule that protects your private pages. That is the whole beginner arc — keys, provider, components, protection, and one server-side user check.

  1. Create a free Clerk app at dashboard.clerk.com and copy your publishable key (pk_test_...) and secret key (sk_test_...) — or let the CLI provision a claimable app for you.
  2. Run npx -y clerk@latest init in your project. It detects Next.js and npm automatically, installs @clerk/nextjs, writes both keys to .env.local, adds <ClerkProvider> to your layout, and creates the middleware file (proxy.ts on Next.js 16+, middleware.ts on 15 and below).
  3. Add sign-in and sign-up screens with Clerk's prebuilt components — <SignInButton />, <SignUpButton />, or the full <SignIn /> and <SignUp /> pages.
  4. Protect your private pages with clerkMiddleware plus a createRouteMatcher rule, so signed-out visitors bounce to sign-in.
  5. Read the user on the server with const { userId } = await auth() in any route or server component, and only load private data when userId exists.

The rest of this guide walks each step in detail, with the key-hygiene rules most tutorials skip and the beginner traps that make old guides fail on today's SDK.

What Is Clerk, Exactly?

Clerk is a hosted user-management and authentication platform, and this clerk tutorial starts with what it replaces: instead of writing your own password hashing, session cookies, password-reset emails, and OAuth flows, you outsource all of it to Clerk and integrate with a few lines of SDK code. Signing up, signing in, sign-out, user profiles, session management, social logins, passkeys, and multi-factor auth are handled by Clerk's service; your app asks the SDK "who is signed in?" and acts on the answer. The beginner decision is build-vs-buy: rolling your own auth is a 2–4 week security project even for experienced developers, because it means password hashing with bcrypt or Argon2, secure session cookies with expiration and renewal, reset-token generation, brute-force lockout, and MFA — while a managed service gives you all of it, SOC 2-audited, in an afternoon. If you want the build-it-yourself path to compare, the Supabase beginner guide walks through auth that lives inside your own backend; Clerk is the hosted alternative, and this guide is the one to follow when you would rather not operate the auth server yourself.

Step 1: Create Your Clerk App and Claim Your Keys

Every Clerk setup starts in the Dashboard: sign up free (no credit card required on the Hobby plan) and create an application, giving it a name like "my-first-app" and choosing your sign-in options — email, phone number, or username as identifiers, and password or passwordless (email code or email link) as the strategy. Clerk then issues two keys: a publishable key (pk_test_...), which is safe to expose in the browser, and a secret key (sk_test_...), which must never appear in client-side code, screenshots, or your repository. If you stay signed out and run npx -y clerk@latest init instead, the CLI provisions a claimable application automatically and writes dev keys into .env.local — you claim the app into your account later. Either way, before your first commit, confirm .env.local is in .gitignore (Next.js scaffolds it that way by default). The single most common beginner breach is a secret key pushed to a public repo — the fix is one line of gitignore, done before the key ever exists in your project.

Step 2: Install the SDK and Wrap Your App

The SDK install depends on your framework, and getting the package name right is what separates working setups from broken ones. For Next.js, run the CLI (npx -y clerk@latest init) or install manually with npm install @clerk/nextjs; for plain React (Vite, Create React App-era projects, and non-Next setups) the package is @clerk/clerk-react. In Next.js, your root layout gets <ClerkProvider> from @clerk/nextjs — and it goes inside <body>, not wrapped around <html>:

import { ClerkProvider } from '@clerk/nextjs'

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

For a plain React app, the same provider comes from @clerk/clerk-react with your publishable key passed as a prop, wrapped around your component tree. The CLI handles all of this for Next.js projects — manual install is only the fallback if init fails, which is why you should not hand-write provider setup first.

Step 3: Add Sign-In and Sign-Up Screens

Clerk ships prebuilt sign-in and sign-up UI, so beginners never have to design login forms or handle password fields directly. The lightest version is buttons in your layout — <SignInButton /> and <SignUpButton /> for signed-out visitors, and <UserButton /> (the profile avatar menu) for signed-in ones — or the <Show when="signed-out"> / <Show when="signed-in"> components to swap between them, wrapped in <Suspense> since <Show> reads the request. The fuller version is dedicated pages rendering the complete <SignIn /> and <SignUp /> components, which include email verification, password rules, and account recovery out of the box. Clerk enforces a minimum 8-character password and checks passwords against leaked-password databases automatically (its default policy follows NIST 800-63B), so your test accounts are held to a real standard — for the reasoning behind that length, read how long should a password be. Either way, never write your own password input to a custom API endpoint when the prebuilt components exist — the moment you touch raw credentials, you own the security of the whole flow.

Step 4: Protect Your Pages with Clerk Middleware

A sign-in screen is useless if a signed-out visitor can just type your dashboard URL directly — middleware is what actually blocks them. Clerk's Next.js middleware protects routes at the edge before the page renders:

import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'

const isPublicRoute = createRouteMatcher(['/sign-in(.*)', '/sign-up(.*)', '/'])

export default clerkMiddleware(async (auth, req) => {
  if (!isPublicRoute(req)) {
    await auth.protect() // redirects to sign-in if not authenticated
  }
})

export const config = {
  matcher: ['/((?!.*\\..*|_next).*)', '/', '/(api|trpc)(.*)'],
}

Name the file proxy.ts on Next.js 16+ and middleware.ts on Next.js 15 and below — the contents are identical, and the CLI creates the right filename for your version. createRouteMatcher takes glob patterns for the pages that stay public (your home page, sign-in, sign-up); every other route gets await auth.protect(), which sends unauthenticated visitors to your sign-in URL automatically. This is the "clerk protected routes" piece of the puzzle, and it is also the part beginners test wrong: test it in an incognito window, not your logged-in browser, or you will think protection is broken when it is actually working.

Step 5: Read the Signed-In User on the Server

The final step is the one that makes your app personal: reading the user on the server so private data only loads for its owner. In any server component or route handler, auth() from @clerk/nextjs/server is async — always await it:

import { auth } from '@clerk/nextjs/server'

export default async function DashboardPage() {
  const { userId } = await auth()
  if (!userId) {
    // middleware normally blocks this, but never trust the client alone
    return <p>Please sign in to view your dashboard.</p>
  }
  // load this user's data only: db.posts.findMany({ where: { authorId: userId } })
  return <h1>Your dashboard</h1>
}

Use auth() for lightweight checks like userId and currentUser() when you need the full user object (name, email, avatar). The golden rule: never make a security decision on the client alone — a signed-in badge in the UI is decoration; the server check in this step is the lock. Client hooks like useUser() are for displaying the name and avatar, not for deciding who sees private data.

How Does Clerk Handle Social Login?

Social login ("Sign in with Google") is a Dashboard toggle, not a code project: in the Clerk Dashboard under your app's authentication settings, enable the Google connection, and the prebuilt sign-in component shows the button automatically. The Hobby free plan includes up to 3 social connections, which covers Google, GitHub, and one more for almost every beginner project. Because the OAuth handshake runs entirely through Clerk, you never handle provider secrets, redirect URIs, or token exchanges yourself — the user picks their Google account, Clerk verifies it, and your auth() check sees the same userId as any other sign-in. Keep this in the "advanced but easy" bucket: enable it after your email sign-in works, not before, so you debug one flow at a time.

Clerk vs Auth0: Which One Should You Start With?

Every beginner compares Clerk to Auth0, the older hosted-auth giant, so here is the honest split for a first project. Clerk's Hobby plan is free with no credit card and covers 50,000 monthly retained users per app; its paid Pro plan is $20/month billed annually. Auth0's free tier covers 25,000 monthly active users, with Essentials at $35/month and Professional at $240/month — and for SSO-heavy B2B apps, Clerk includes one enterprise connection on Pro with published overage pricing, while larger Auth0 SSO needs move into custom pricing.

QuestionClerkAuth0
Free tier50,000 monthly retained users per app, no credit card25,000 monthly active users
Cheapest paid plan$20/mo (Pro, billed annually)$35/mo (Essentials)
Prebuilt sign-in/sign-up UIIncluded, drop-in componentsAvailable (Universal Login)
Organizations (B2B)Included add-on, 100 orgs free, 20 members eachPaid tiers for full B2B
Best forReact/Next.js beginners who want UI + auth togetherTeams needing broad enterprise SSO coverage

For a first app, pick Clerk when you want the prebuilt UI and the auth backend from one provider with minimal code; pick Auth0 when your requirements document already says "enterprise SSO" and you have budget. Either choice beats hand-rolled auth — and either one you pick, the key-hygiene rules in this guide apply unchanged.

What Are Clerk Organizations (And Can You Skip Them?)

Clerk Organizations are its B2B feature: workspaces where multiple users share an account — think a team, a company, or a classroom — with Admin and Member roles, invitations, and custom permissions. The free tier includes 100 organizations per app with up to 20 members each, which is generous for a starter. But organizations are an advanced section, not beginner core: you enable them with npx -y clerk@latest enable orgs, and they add concepts (org slugs, roles, invitations) that confuse a first project. Build your single-user flow first — sign-in, protected pages, server-side user check — and add organizations only when a real user asks "can my team share this?" That question has a clean answer in Clerk, and waiting for it keeps your first app shippable.

5 Mistakes Beginners Make with Clerk

Most broken Clerk setups come from the same short list. Run through it before you ask for help:

MistakeWhat happensThe fix
Secret key in the repoAnyone with the repo can impersonate your backend to ClerkCLERK_SECRET_KEY only in .env.local, which is gitignored before the first commit
Following a 2023–2024 tutorialRetired props like frontendApi and ReactDOM.render fail silently or throwUse the current CLI (clerk@latest init) or this guide's code only
Trusting client-side auth stateAnyone can flip a UI badge; private data leaksEvery protected route checks await auth() on the server
Wrong middleware filenameProtection never runs — dashboard opens for everyoneproxy.ts on Next.js 16+, middleware.ts on 15 and below
Testing in your logged-in browserYou think protection works when you never actually tested itAlways verify protected routes in an incognito window

Is Clerk Free?

Yes, for almost every beginner project. The Hobby plan costs $0 with no credit card and includes unlimited applications, 50,000 monthly retained users per app, the prebuilt sign-in/sign-up/profile UIs, email and social sign-in (up to 3 social connections), passkeys, brute-force prevention, and a 7-day fixed session lifetime. You outgrow it when you need MFA for users, custom session lifetimes, removed "Secured by Clerk" branding, or more than 50,000 retained users — at which point Pro is $20/month billed annually. The dev-instance trick is worth knowing: Pro-tier features are available to try in your development instance without a trial clock, so you can evaluate the paid features before your app earns a dollar.

Sources

  • Clerk Docs — Next.js Quickstart (App Router): npx -y clerk@latest init flow, proxy.ts vs middleware.ts naming rule, <ClerkProvider> inside <body>, async await auth(), npx -y clerk@latest enable orgs and doctor commands (crawled 2026-10-30).
  • Clerk Pricing (clerk.com/pricing): Hobby free, no credit card, 50,000 MRUs per app, unlimited applications, up to 3 social connections, fixed 7-day session lifetime, 100 orgs with 20 members and Admin/Member roles, Pro $20/mo billed annually, brute-force prevention on by default (crawled 2026-10-30).
  • Clerk Pricing FAQ: Auth0 comparison — Auth0 free tier 25,000 MAU, Essentials $35/mo, Professional $240/mo (crawled 2026-10-30).
  • Clerk Docs — Sign-up and sign-in options: email/phone/username identifiers, password and passwordless strategies, minimum 8-character password, leaked-password protection (crawled 2026-10-30).
  • StackNotice — "Clerk + Next.js Authentication Complete Guide (2026)": clerkMiddleware + createRouteMatcher pattern, await auth.protect(), NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY / CLERK_SECRET_KEY env names, currentUser() for the full user object (crawled 2026-10-30).
  • eliteai.tools — Clerk authentication skill: auth() for userId checks, never trust client-side auth state for security decisions, middleware matcher config (crawled 2026-10-30).

Frequently Asked Questions

How long does it take to add Clerk to a Next.js app?

About 10–30 minutes. Run npx -y clerk@latest init, add prebuilt sign-in and sign-up buttons to your layout, and add the middleware matcher for protected routes. Most of that time is the Dashboard setup and testing sign-up in an incognito window — the code itself is under 50 lines.

Do I need a credit card to start using Clerk?

No. The Hobby plan is free with no credit card required and covers 50,000 monthly retained users per app, unlimited applications, prebuilt UIs, and up to 3 social connections. You only pay if you outgrow those limits or need Pro features like MFA.

Where do I put my Clerk keys?

Both keys go in .env.local at your project root: NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY (safe for the browser) and CLERK_SECRET_KEY (server only, never committed). Confirm .env.local is in .gitignore before your first commit — a pushed secret key must be rotated in the Dashboard immediately.

Can I use Clerk with React instead of Next.js?

Yes. Install @clerk/clerk-react and wrap your app in <ClerkProvider> with your publishable key. The prebuilt <SignIn /> and <SignUp /> components, useUser() hook, and route guards all work the same — only the Next.js-specific middleware and server auth() are replaced by your router's guards and Clerk's backend SDK.

Should I build my own auth instead of using Clerk?

Almost never for a first app. Secure hand-rolled auth means password hashing, session cookies, reset flows, brute-force protection, and MFA — weeks of security-critical work — while Clerk gives you all of it, SOC 2-audited, in one afternoon. Build your own only when you have a specific requirement (full data ownership, a custom flow) that a hosted service cannot meet.

Featured on Twelve Tools Launch Llama Tools Launch your MCP