---
name: add-clerk-auth
description: Adds Clerk authentication to a Next.js or React app - install the SDK, set the keys, wrap the app in ClerkProvider, add the hosted sign-in components, protect routes with clerkMiddleware, and check the user on the server before reading data. Use when the user mentions Clerk, wants Google sign-in through Clerk, or asks for Clerk middleware or protected pages.
license: CC-BY-4.0
metadata:
  category: backend
  tags: "clerk,auth,nextjs,react"
  author: johnny-bravo
  version: "1.0"
  updated: "2026-11-02"
  status: published
  aliases: "clerk login, clerk middleware, clerk nextjs"
---

# Add Clerk auth

Clerk handles sign-up, sign-in, social logins and user profiles for you. Your job is to wire it in and protect the right pages and data.

## When to use
- You want login with email or Google without building it.
- Some pages, such as a dashboard, should only be for signed-in users.
- You already chose Clerk. For Supabase Auth, use set-up-supabase-auth.

## Steps
1. Create an app in the Clerk dashboard and choose sign-in methods (email, Google, GitHub).
2. Install the SDK for your framework, such as `npm install @clerk/nextjs`.
3. Add `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` and `CLERK_SECRET_KEY` to `.env.local` and to your host.
4. Wrap the app in `<ClerkProvider>` in the root layout.
5. Add sign-in and sign-up pages with Clerk's `<SignIn />` and `<SignUp />` components, or use the hosted pages.
6. Add a middleware file using `clerkMiddleware()` and mark which routes need a signed-in user.
7. Show `<UserButton />` in the header for account and sign-out.
8. On the server, call `auth()` in every route handler and server action that touches user data, and return 401 when there is no user.
9. Store the Clerk user id on your own records (such as `owner_id`) and filter queries by it.
10. Test signed out, signed in, and signed in as a different user.

## Gotchas
- Middleware alone is not enough. Check the user on the server before every read or write of private data.
- The secret key is server-only. Never expose it with a public prefix.
- Add your production domain in Clerk and switch to production keys before launch.
- Sync users to your database with Clerk webhooks if you need profiles there, and verify the webhook signature.

## Portability
Works with Next.js App Router and Pages Router, Remix, Astro and plain React. If you use another auth provider such as Auth.js or Supabase Auth instead, the same rule applies: protect routes and check the user on the server.

## Example prompt
"Add Clerk sign-in with Google and email to my Next.js app, protect /dashboard, and make sure users only see their own projects."

## Done when
- Users can sign up, sign in and sign out.
- Protected pages redirect signed-out visitors.
- Server code checks the user, and one user cannot read another user's data.

---
House original by TheSkillVault (CC-BY-4.0).
