Getting started overview
Clerk provides developer tools for authentication and user management, particularly focused on web applications built with frameworks like React and Next.js. The getting started process typically involves several steps: signing up for a Clerk account, creating an application instance, obtaining API keys, and integrating these keys with a Clerk SDK within a project. For web applications, Clerk offers pre-built UI components that can be integrated to handle common authentication flows, such as sign-in, sign-up, and user profile management, often reducing the amount of custom code required to implement these features Clerk developer references.
The primary goal of this guide is to demonstrate how to achieve a functional authentication setup and make a first authenticated request using Clerk.
Clerk Getting Started Reference
The following table outlines the essential steps to get started with Clerk:
| Step | What to Do | Where |
|---|---|---|
| 1. Sign Up for Clerk | Create a new Clerk account. | Clerk sign-up page |
| 2. Create New Application | From the Clerk Dashboard, create a new application instance. | Clerk Dashboard > Applications |
| 3. Retrieve API Keys | Locate and copy your Public Frontend API key and Secret Key. | Clerk Dashboard > Your Application > API Keys |
| 4. Configure Environment | Set your API keys as environment variables in your project. | .env.local (Next.js/React) or equivalent |
| 5. Install SDK | Add the relevant Clerk SDK to your project. | Terminal: npm install @clerk/nextjs (for Next.js) |
| 6. Wrap Application | Integrate the <ClerkProvider> component into your application's root. |
_app.js or layout.js (Next.js) |
| 7. Add Authentication UI | Implement Clerk's pre-built UI components (e.g., <SignIn>, <SignUp>). |
Relevant page components in your application |
| 8. Protect Routes | Use Clerk middleware or HOCs to protect specific routes. | middleware.ts (Next.js) or route components |
| 9. Make Authenticated Request | Access user session information to make an authenticated call. | Frontend or Backend API routes |
Create an account and get keys
To begin using Clerk, you must first create an account and set up an application instance to obtain your API keys. Clerk offers a free tier that supports up to 10,000 monthly active users (MAUs) and includes all standard features, making it suitable for initial development and testing Clerk pricing details.
- Sign Up for a Clerk Account: Navigate to the Clerk sign-up page and complete the registration process. You can use an email address, Google, or GitHub for signup.
- Create a New Application: After signing in, you will be redirected to the Clerk Dashboard. Click on the "Add application" button. You'll be prompted to choose an application type (e.g., Next.js, React, Node.js). Select the option that best matches your project. For front-end heavy applications, choosing Next.js or React will guide you through relevant setup steps.
- Retrieve API Keys: Once your application is created, you will be directed to its overview page. Here, you will find your Public Frontend API Key (prefixed with
pk_) and your Secret Key (prefixed withsk_). The Public Frontend API Key is used in your client-side code, while the Secret Key should only be used in secure backend environments. Copy both of these keys.
It is critical to handle your Secret Key securely, typically by storing it as an environment variable and never exposing it in client-side code or public repositories. For example, in a Next.js application, you would add these to a .env.local file:
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY="pk_YOUR_PUBLIC_KEY"
CLERK_SECRET_KEY="sk_YOUR_SECRET_KEY"
Ensure these environment variables are correctly loaded into your application's build process. For a local development environment, restarting your development server after adding or changing environment variables is often necessary.
Your first request
Making an authenticated request with Clerk primarily involves ensuring the user is signed in and then using the available session token to authorize API calls. For web applications, Clerk's SDKs abstract much of the token management, making it straightforward to protect routes and access user information.
Example: Next.js with Clerk
This example demonstrates how to set up a basic Next.js application, integrate Clerk, and make an authenticated request to a protected API route.
1. Initialize a Next.js Project:
npx create-next-app@latest my-clerk-app --typescript --eslint
cd my-clerk-app
2. Install Clerk SDK:
npm install @clerk/nextjs
3. Configure Environment Variables:
Create a .env.local file in your project root and add your keys:
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY="pk_YOUR_PUBLIC_KEY"
CLERK_SECRET_KEY="sk_YOUR_SECRET_KEY"
4. Wrap Your Application with ClerkProvider:
Modify src/app/layout.tsx (for App Router) or src/pages/_app.tsx (for Pages Router) to include the ClerkProvider. For App Router, it might look like this:
// src/app/layout.tsx
import { ClerkProvider } from '@clerk/nextjs';
import './globals.css';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<ClerkProvider>
<html lang="en">
<body>{children}</body>
</html>
</ClerkProvider>
);
}
5. Add Authentication UI:
Create a simple sign-in page, for example, src/app/sign-in/[[...sign-in]]/page.tsx:
// src/app/sign-in/[[...sign-in]]/page.tsx
import { SignIn } from '@clerk/nextjs';
export default function Page() {
return <SignIn />;
}
And a sign-up page, src/app/sign-up/[[...sign-up]]/page.tsx:
// src/app/sign-up/[[...sign-up]]/page.tsx
import { SignUp } from '@clerk/nextjs';
export default function Page() {
return <SignUp />;
}
6. Protect Routes with Middleware:
Create middleware.ts at the root of your project:
// middleware.ts
import { authMiddleware } from '@clerk/nextjs';
export default authMiddleware({
publicRoutes: ['/sign-in(.*)', '/sign-up(.*)', '/'], // Allow access to public routes
});
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
This middleware ensures that all routes except those specified in publicRoutes require authentication.
7. Create a Protected API Route:
Create an API route, for example, src/app/api/hello/route.ts, and use auth() to access session information:
// src/app/api/hello/route.ts
import { auth } from '@clerk/nextjs';
import { NextResponse } from 'next/server';
export async function GET() {
const { userId } = auth();
if (!userId) {
return new NextResponse('Unauthorized', { status: 401 });
}
// In a real application, you might fetch user-specific data here
return NextResponse.json({ message: `Hello, user ${userId}! This is a protected API route.` });
}
8. Make a Frontend Call to the Protected API:
Modify your main page (e.g., src/app/page.tsx) to include a button that triggers a call to this protected API route:
// src/app/page.tsx
'use client';
import { UserButton, useUser, SignOutButton } from '@clerk/nextjs';
import { useState } from 'react';
export default function Home() {
const { isSignedIn, user } = useUser();
const [apiResponse, setApiResponse] = useState<string | null>(null);
const callProtectedApi = async () => {
if (!isSignedIn) {
setApiResponse('Please sign in first.');
return;
}
try {
const res = await fetch('/api/hello');
const data = await res.json();
setApiResponse(data.message);
} catch (error) {
setApiResponse('Error calling protected API.');
console.error(error);
}
};
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<div className="z-10 w-full max-w-5xl items-center justify-between font-mono text-sm lg:flex">
{isSignedIn ? (
<div className="flex items-center gap-4">
<UserButton afterSignOutUrl="/" />
<p>Welcome, {user?.firstName}!</p>
<SignOutButton />
</div>
) : (
<a href="/sign-in">Sign In</a>
)}
</div>
<div className="relative flex place-items-center before:absolute before:h-[300px] before:w-full before:-translate-x-1/2 before:rounded-full before:bg-gradient-radial before:from-white before:to-transparent before:blur-2xl before:content-[''] after:absolute after:-z-20 after:h-[180px] after:w-full after:translate-x-1/3 after:bg-gradient-conic after:from-sky-200 after:via-blue-200 after:blur-2xl after:content-[''] before:dark:bg-gradient-to-br before:dark:from-transparent before:dark:to-blue-700 before:dark:opacity-10 after:dark:from-sky-900 after:dark:via-[#0141ff] after:dark:opacity-40 sm:before:w-[480px] sm:after:w-[240px] before:lg:h-[360px]">
<h1 className="relative dark:drop-shadow-[0_0_0.3rem_#ffffff70] dark:invert">
Clerk Next.js Example
</h1>
</div>
<div className="mb-32 grid text-center lg:mb-0 lg:w-full lg:max-w-5xl lg:grid-cols-4 lg:text-left">
<button
onClick={callProtectedApi}
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
>
<h2 className="mb-3 text-2xl font-semibold">
Call Protected API{' '}
<span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
->
</span>
</h2>
<p className="m-0 max-w-[30ch] text-sm opacity-50">
Click to fetch data from a Clerk-protected backend route.
</p>
</button>
{apiResponse && <p className="mt-4 text-center lg:text-left col-span-4">API Response: {apiResponse}</p>}
</div>
</main>
);
}
After running npm run dev and navigating to http://localhost:3000, you should be able to sign in or sign up, and then click the "Call Protected API" button to see the authenticated response.
Common next steps
Once you have a basic Clerk integration working, several common next steps can enhance your application's authentication and user management capabilities:
- Customize UI Components: Clerk's pre-built UI components can be styled to match your application's branding. This often involves using CSS variables or providing custom themes Clerk UI customization guide.
- Implement Multi-tenancy (Organizations): For B2B SaaS applications, Clerk's Organizations feature allows you to manage multiple teams or companies within a single application. This involves enabling organizations in your Clerk dashboard and using components like
<OrganizationSwitcher>Clerk Organizations documentation. - Add Social Logins (OAuth): Configure additional OAuth providers (e.g., Google, GitHub, Facebook) in your Clerk Dashboard to offer users more sign-in options.
- Implement Roles and Permissions (RBAC): Define custom roles (e.g., 'admin', 'editor') and assign them to users within your Clerk application. You can then use these roles to control access to specific features or data in your application Clerk roles and permissions.
- Webhooks for Backend Logic: Set up webhooks to trigger backend actions based on user events (e.g., user created, user updated). This is useful for synchronizing user data with other services or performing custom operations Clerk webhooks guide. For general webhook security practices, refer to resources like Twilio's webhook security guide.
- Explore Backend SDKs: While this guide focuses on frontend integration, Clerk also offers backend SDKs for Node.js, Go, Python, and Ruby. These can be used to manage users, sessions, and organizations directly from your backend services without relying on client-side tokens for sensitive operations Clerk backend SDK references.
- User Impersonation: For support or administrative purposes, enable user impersonation to temporarily assume the identity of another user. This can be configured through the Clerk Dashboard and typically requires specific permissions.
Troubleshooting the first call
When encountering issues with your initial Clerk integration or authenticated requests, consider the following common troubleshooting steps:
- Environment Variables: Double-check that your
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEYandCLERK_SECRET_KEYare correctly set in your.env.localfile and that your application server has been restarted to pick up these changes. Mismatched or missing keys are a frequent source of authentication failures. - Clerk Dashboard Configuration: Verify that your application in the Clerk Dashboard has the correct domain configured. For local development, ensure
localhost:3000(or your specific development port) is listed under "Allowed Callback URLs" and "Allowed origins" Clerk deployment configuration. - Middleware Configuration: If using Next.js, ensure your
middleware.tsfile is correctly configured, especially thepublicRoutesarray. If a route you expect to be public is being protected, or vice-versa, the middleware might be misconfigured. - SDK Version Compatibility: Ensure you are using a compatible version of the Clerk SDK with your framework (e.g.,
@clerk/nextjsfor Next.js). Refer to the Clerk documentation for specific version requirements. - Browser Console Errors: Open your browser's developer console (F12) to check for any JavaScript errors related to Clerk. These can often provide specific clues about configuration issues or API call failures.
- Network Tab Inspection: Use the browser's network tab to inspect API calls made by Clerk. Look for failed requests (e.g., 401 Unauthorized, 403 Forbidden) and examine their response bodies for error messages from Clerk's API.
- Clerk Debugging Tools: Clerk provides debugging information in the developer console. Look for messages prefixed with
[Clerk], which can indicate issues with initialization or authentication state. - Session State: Verify that a user is actually signed in when making an authenticated request. You can use
useUser().isSignedInorauth().userId(in server components/API routes) to check the authentication state. - CORS Issues: If you are making requests from a different origin than your Clerk application, ensure that Cross-Origin Resource Sharing (CORS) is correctly configured, both in your Clerk Dashboard and potentially in your backend API.