CLAUDE.md Template for Clerk Auth in Next.js
A production-ready CLAUDE.md template for building Clerk authentication in Next.js App Router projects with protected routes, middleware, user metadata, role-based access, server-side authorization, and secure SaaS workflows.
Target User
Next.js developers, SaaS builders, full-stack developers, AI product builders, and teams implementing secure authentication with Clerk
Use Cases
- Next.js SaaS authentication
- Protected dashboard routes
- Admin-only pages
- Role-based access control
- Clerk organizations
- User metadata workflows
- Subscription-gated pages
- Secure API route authorization
Markdown Template
CLAUDE.md Template for Clerk Auth in Next.js
# CLAUDE.md: Clerk Auth in Next.js Development Guide
You are helping build a production-grade Next.js App Router application using Clerk for authentication and authorization.
The application must prioritize secure server-side authorization, protected routes, role-based access, clear user flows, and maintainable authentication logic.
## Core Principle
Do not treat authentication as only a UI problem.
Hiding buttons or links is not security.
Every protected page, API route, server action, database operation, and privileged workflow must enforce authorization on the server side.
## Application Goals
The system should support:
- User sign up
- User sign in
- User sign out
- Protected dashboard routes
- Public marketing pages
- Server-side user checks
- Secure API route authorization
- Role-based access control
- Admin-only sections
- Optional organization-based access
- Optional subscription or plan gating
- User metadata handling
- Clear unauthorized and unauthenticated states
## Architecture Guidelines
Use a modular auth architecture.
Separate the system into these layers:
1. Clerk provider setup
2. Middleware route protection
3. Server-side auth helper functions
4. Role and permission helpers
5. User metadata helpers
6. Protected page layouts
7. Protected API route handlers
8. Unauthorized and onboarding UI
9. Admin access workflows
10. Audit and debugging utilities
Avoid spreading raw auth logic across many files.
Create reusable helper functions such as requireUser, requireAdmin, requireOrganization, and getCurrentUserProfile.
## Clerk Setup Rules
Use Clerk according to the current Next.js App Router setup.
The root layout should wrap the application with the Clerk provider.
Sign-in and sign-up pages should use Clerk components or custom Clerk flows.
Environment variables must stay server-side where required.
Never expose Clerk secret keys to the browser.
Expected environment variables may include:
- NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
- CLERK_SECRET_KEY
- NEXT_PUBLIC_CLERK_SIGN_IN_URL
- NEXT_PUBLIC_CLERK_SIGN_UP_URL
- NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL
- NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL
Do not hardcode secrets.
## Middleware Rules
Use middleware to protect route groups such as:
- /dashboard
- /admin
- /settings
- /billing
- /api/private
- /api/admin
Middleware should distinguish between public routes and protected routes.
Public routes may include:
- /
- /blog
- /pricing
- /about
- /sign-in
- /sign-up
Middleware is useful for broad protection, but it is not enough by itself.
Always add server-side authorization inside sensitive pages, route handlers, server actions, and database writes.
## Server-Side Authorization Rules
Every protected server component should verify the current user.
Every protected API route should verify the current user.
Every admin API route should verify admin permission.
Every database operation should be scoped by userId or organizationId.
Never trust userId from the client request body.
Always derive user identity from Clerk server-side auth.
## Helper Function Rules
Create reusable helpers for authorization.
Examples:
requireUser:
- checks whether a user is signed in
- redirects or throws if not authenticated
- returns userId and user information
requireAdmin:
- checks whether a user is signed in
- checks whether user has admin role
- blocks access if not admin
requireOrganization:
- checks whether a user belongs to an organization
- validates organization access
- scopes queries by organizationId
Do not duplicate this logic in every route.
## Role-Based Access Control Rules
Roles should be explicit.
Possible roles:
- user
- member
- manager
- admin
- owner
Admin access should not be inferred from email address unless explicitly required for a small internal tool.
For production SaaS, prefer metadata or database-backed role records.
Role checks should happen on the server.
Client-side role checks can improve UX, but they must not be the only protection.
## Clerk Metadata Rules
Use Clerk metadata carefully.
Public metadata can be read by the frontend.
Private metadata should be used for sensitive internal fields.
Unsafe metadata should not be trusted for security-critical logic unless properly controlled.
Useful metadata fields may include:
- role
- onboardingComplete
- plan
- customerId
- organizationRole
Keep metadata small and purposeful.
Do not store large application data in Clerk metadata.
Use your application database for product data, records, analytics, and business entities.
## Database Access Rules
Every database record that belongs to a user should include userId.
Every database record that belongs to an organization should include organizationId.
When reading data:
- filter by authenticated userId or organizationId
- never return records from another user
- never trust client-provided ownership fields
When writing data:
- attach userId or organizationId on the server
- validate input
- check permissions before updates or deletes
## Protected API Route Rules
API routes should follow this pattern:
1. Read Clerk auth on the server
2. Reject unauthenticated users
3. Validate request input
4. Check role or ownership
5. Perform the database operation
6. Return a safe response
Never expose stack traces, secrets, or raw database errors to the client.
## Server Action Rules
If using server actions:
- check auth inside the server action
- validate all input
- check ownership before changing data
- return safe errors
- avoid trusting hidden form fields for userId or role
Server actions must not assume the UI already protected the action.
## Admin Panel Rules
Admin pages must require admin access on the server.
Admin API routes must require admin access on the server.
Admin UI should show:
- authenticated admin identity
- user management tools if needed
- audit information if needed
- clear unauthorized states
Do not allow non-admin users to fetch admin data even if the admin UI is hidden.
## Organization Access Rules
If using Clerk organizations:
- verify active organization context
- validate membership
- scope records by organizationId
- distinguish organization roles from global app roles
- prevent cross-organization data access
Do not assume the selected organization from the client is valid.
Validate organization access on the server.
## Subscription and Plan Gating Rules
If the app has paid features:
- store subscription status in the database or trusted metadata
- verify plan access on the server
- protect premium API routes
- protect premium server actions
- show upgrade UI on the client
Do not rely only on disabled buttons or hidden links for billing enforcement.
## UI Expectations
The user interface should include:
- sign-in page
- sign-up page
- user button or profile menu
- protected dashboard
- loading states
- unauthorized page
- onboarding state if needed
- admin-only navigation when appropriate
- clear sign-out behavior
Client-side UI should improve experience, but server-side checks provide security.
## Error Handling
Handle common auth states clearly:
- unauthenticated user
- unauthorized user
- missing role
- missing organization
- incomplete onboarding
- expired session
- invalid request
- forbidden resource access
Return helpful messages without exposing secrets.
## Security Rules
Never expose CLERK_SECRET_KEY to the client.
Never trust client-provided userId, role, organizationId, or plan.
Always derive identity from Clerk server-side auth.
Always check ownership before reading or mutating records.
Always validate inputs before database writes.
Protect both pages and APIs.
Do not rely only on middleware for sensitive authorization.
Do not rely only on client-side checks.
## Code Quality Rules
Write clean, modular, production-oriented code.
Prefer:
- reusable auth helpers
- explicit role checks
- clear route protection
- server-side authorization
- schema validation
- safe redirects
- safe error responses
- minimal duplicated auth logic
Avoid:
- hardcoded user IDs
- hardcoded secret keys
- checking admin only in the UI
- trusting request body userId
- unprotected API routes
- unscoped database queries
- scattered role logic
- storing large app data in Clerk metadata
## Preferred Behavior
When a user is not signed in:
Redirect to sign in or return 401 for API routes.
When a user is signed in but not allowed:
Show an unauthorized page or return 403.
When a user belongs to the wrong organization:
Block access and do not reveal private resource details.
When a user has the correct role:
Allow the action and scope all data correctly.
## Development Style
Before implementing an auth feature, reason about:
- who can access this page
- who can call this API route
- who owns this database record
- whether this action needs a role
- whether this action needs an organization
- whether this action needs a paid plan
- what happens if the user is unauthenticated
- what happens if the user is authenticated but unauthorized
Build the smallest secure version first, then improve onboarding, organization support, billing gates, admin workflows, and audit logs.What is this CLAUDE.md template for?
This CLAUDE.md template is designed for developers building authentication and authorization workflows in Next.js App Router applications using Clerk. It gives an AI coding assistant clear instructions about protected routes, middleware, server-side auth checks, user metadata, admin access, organization support, and secure SaaS patterns.
The goal is simple: avoid shallow authentication code that only hides UI elements. A production Next.js application must protect routes, API handlers, server actions, database operations, and role-based workflows on the server side.
When to use this template
Use this template when your project uses Clerk for login, signup, protected dashboards, admin panels, organization-based access, user metadata, subscriptions, or SaaS authorization. It is especially useful for Next.js App Router projects that need secure access control beyond basic sign-in buttons.
Recommended project structure
project-root/
app/
layout.js
page.js
sign-in/
[[...sign-in]]/
page.jsx
sign-up/
[[...sign-up]]/
page.jsx
dashboard/
layout.js
page.js
admin/
page.js
api/
user/
route.js
admin/
route.js
components/
auth/
dashboard/
admin/
ui/
lib/
auth/
require-user.js
require-admin.js
require-organization.js
roles.js
metadata.js
db/
utils/
middleware.js
README.md
CLAUDE.md
CLAUDE.md Template
# CLAUDE.md: Clerk Auth in Next.js Development Guide
You are helping build a production-grade Next.js App Router application using Clerk for authentication and authorization.
The application must prioritize secure server-side authorization, protected routes, role-based access, clear user flows, and maintainable authentication logic.
## Core Principle
Do not treat authentication as only a UI problem.
Hiding buttons or links is not security.
Every protected page, API route, server action, database operation, and privileged workflow must enforce authorization on the server side.
## Application Goals
The system should support:
- User sign up
- User sign in
- User sign out
- Protected dashboard routes
- Public marketing pages
- Server-side user checks
- Secure API route authorization
- Role-based access control
- Admin-only sections
- Optional organization-based access
- Optional subscription or plan gating
- User metadata handling
- Clear unauthorized and unauthenticated states
## Architecture Guidelines
Use a modular auth architecture.
Separate the system into these layers:
1. Clerk provider setup
2. Middleware route protection
3. Server-side auth helper functions
4. Role and permission helpers
5. User metadata helpers
6. Protected page layouts
7. Protected API route handlers
8. Unauthorized and onboarding UI
9. Admin access workflows
10. Audit and debugging utilities
Avoid spreading raw auth logic across many files.
Create reusable helper functions such as requireUser, requireAdmin, requireOrganization, and getCurrentUserProfile.
## Clerk Setup Rules
Use Clerk according to the current Next.js App Router setup.
The root layout should wrap the application with the Clerk provider.
Sign-in and sign-up pages should use Clerk components or custom Clerk flows.
Environment variables must stay server-side where required.
Never expose Clerk secret keys to the browser.
Expected environment variables may include:
- NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
- CLERK_SECRET_KEY
- NEXT_PUBLIC_CLERK_SIGN_IN_URL
- NEXT_PUBLIC_CLERK_SIGN_UP_URL
- NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL
- NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL
Do not hardcode secrets.
## Middleware Rules
Use middleware to protect route groups such as:
- /dashboard
- /admin
- /settings
- /billing
- /api/private
- /api/admin
Middleware should distinguish between public routes and protected routes.
Public routes may include:
- /
- /blog
- /pricing
- /about
- /sign-in
- /sign-up
Middleware is useful for broad protection, but it is not enough by itself.
Always add server-side authorization inside sensitive pages, route handlers, server actions, and database writes.
## Server-Side Authorization Rules
Every protected server component should verify the current user.
Every protected API route should verify the current user.
Every admin API route should verify admin permission.
Every database operation should be scoped by userId or organizationId.
Never trust userId from the client request body.
Always derive user identity from Clerk server-side auth.
## Helper Function Rules
Create reusable helpers for authorization.
Examples:
requireUser:
- checks whether a user is signed in
- redirects or throws if not authenticated
- returns userId and user information
requireAdmin:
- checks whether a user is signed in
- checks whether user has admin role
- blocks access if not admin
requireOrganization:
- checks whether a user belongs to an organization
- validates organization access
- scopes queries by organizationId
Do not duplicate this logic in every route.
## Role-Based Access Control Rules
Roles should be explicit.
Possible roles:
- user
- member
- manager
- admin
- owner
Admin access should not be inferred from email address unless explicitly required for a small internal tool.
For production SaaS, prefer metadata or database-backed role records.
Role checks should happen on the server.
Client-side role checks can improve UX, but they must not be the only protection.
## Clerk Metadata Rules
Use Clerk metadata carefully.
Public metadata can be read by the frontend.
Private metadata should be used for sensitive internal fields.
Unsafe metadata should not be trusted for security-critical logic unless properly controlled.
Useful metadata fields may include:
- role
- onboardingComplete
- plan
- customerId
- organizationRole
Keep metadata small and purposeful.
Do not store large application data in Clerk metadata.
Use your application database for product data, records, analytics, and business entities.
## Database Access Rules
Every database record that belongs to a user should include userId.
Every database record that belongs to an organization should include organizationId.
When reading data:
- filter by authenticated userId or organizationId
- never return records from another user
- never trust client-provided ownership fields
When writing data:
- attach userId or organizationId on the server
- validate input
- check permissions before updates or deletes
## Protected API Route Rules
API routes should follow this pattern:
1. Read Clerk auth on the server
2. Reject unauthenticated users
3. Validate request input
4. Check role or ownership
5. Perform the database operation
6. Return a safe response
Never expose stack traces, secrets, or raw database errors to the client.
## Server Action Rules
If using server actions:
- check auth inside the server action
- validate all input
- check ownership before changing data
- return safe errors
- avoid trusting hidden form fields for userId or role
Server actions must not assume the UI already protected the action.
## Admin Panel Rules
Admin pages must require admin access on the server.
Admin API routes must require admin access on the server.
Admin UI should show:
- authenticated admin identity
- user management tools if needed
- audit information if needed
- clear unauthorized states
Do not allow non-admin users to fetch admin data even if the admin UI is hidden.
## Organization Access Rules
If using Clerk organizations:
- verify active organization context
- validate membership
- scope records by organizationId
- distinguish organization roles from global app roles
- prevent cross-organization data access
Do not assume the selected organization from the client is valid.
Validate organization access on the server.
## Subscription and Plan Gating Rules
If the app has paid features:
- store subscription status in the database or trusted metadata
- verify plan access on the server
- protect premium API routes
- protect premium server actions
- show upgrade UI on the client
Do not rely only on disabled buttons or hidden links for billing enforcement.
## UI Expectations
The user interface should include:
- sign-in page
- sign-up page
- user button or profile menu
- protected dashboard
- loading states
- unauthorized page
- onboarding state if needed
- admin-only navigation when appropriate
- clear sign-out behavior
Client-side UI should improve experience, but server-side checks provide security.
## Error Handling
Handle common auth states clearly:
- unauthenticated user
- unauthorized user
- missing role
- missing organization
- incomplete onboarding
- expired session
- invalid request
- forbidden resource access
Return helpful messages without exposing secrets.
## Security Rules
Never expose CLERK_SECRET_KEY to the client.
Never trust client-provided userId, role, organizationId, or plan.
Always derive identity from Clerk server-side auth.
Always check ownership before reading or mutating records.
Always validate inputs before database writes.
Protect both pages and APIs.
Do not rely only on middleware for sensitive authorization.
Do not rely only on client-side checks.
## Code Quality Rules
Write clean, modular, production-oriented code.
Prefer:
- reusable auth helpers
- explicit role checks
- clear route protection
- server-side authorization
- schema validation
- safe redirects
- safe error responses
- minimal duplicated auth logic
Avoid:
- hardcoded user IDs
- hardcoded secret keys
- checking admin only in the UI
- trusting request body userId
- unprotected API routes
- unscoped database queries
- scattered role logic
- storing large app data in Clerk metadata
## Preferred Behavior
When a user is not signed in:
Redirect to sign in or return 401 for API routes.
When a user is signed in but not allowed:
Show an unauthorized page or return 403.
When a user belongs to the wrong organization:
Block access and do not reveal private resource details.
When a user has the correct role:
Allow the action and scope all data correctly.
## Development Style
Before implementing an auth feature, reason about:
- who can access this page
- who can call this API route
- who owns this database record
- whether this action needs a role
- whether this action needs an organization
- whether this action needs a paid plan
- what happens if the user is unauthenticated
- what happens if the user is authenticated but unauthorized
Build the smallest secure version first, then improve onboarding, organization support, billing gates, admin workflows, and audit logs.
Why this template matters
Many Next.js authentication implementations only protect the visual interface. That is not enough. A secure SaaS app must protect server components, route handlers, server actions, and database operations with real server-side authorization.
This template gives your AI coding assistant a clear operating manual so it produces Clerk authentication code that is safer, cleaner, and closer to production quality.
Recommended additions
- Add reusable
requireUser,requireAdmin, andrequireOrganizationhelpers. - Add protected dashboard and admin route groups.
- Add server-side role checks for sensitive pages and API routes.
- Add organization-level data scoping where required.
- Add unauthorized and onboarding pages.
- Add audit logging for admin actions.
FAQ
Can this CLAUDE.md template be used with Next.js App Router?
Yes. It is designed specifically for Next.js App Router projects using Clerk authentication.
Is Clerk middleware enough to secure my app?
No. Middleware is useful for broad route protection, but sensitive pages, API routes, server actions, and database operations should also perform server-side authorization checks.
Should I store roles in Clerk metadata?
You can store small role or plan fields in Clerk metadata, but production applications may also use a database-backed role system depending on complexity and audit requirements.
Can this template support admin-only dashboards?
Yes. It includes guidance for admin-only pages, admin API routes, reusable admin checks, and safe unauthorized states.
Can this template support Clerk organizations?
Yes. It can be extended to support organization membership, organization roles, active organization context, and organization-scoped database records.
About the author
Suhas Bhairav is a systems architect and applied AI researcher focused on production-grade AI systems, RAG, knowledge graphs, AI agents, and enterprise AI implementation.