Authentication overview

Clerk offers an Identity-as-a-Service (IDaaS) platform designed to streamline user authentication and authorization for web and mobile applications. It positions itself as a developer-first solution, providing pre-built UI components and backend SDKs to accelerate the implementation of user management flows. The system handles various authentication methods, session management, and user data storage, aiming to reduce the boilerplate code typically associated with identity solutions.

Clerk's architecture emphasizes integration with modern frontend frameworks, particularly those within the React ecosystem like Next.js, Remix, and Expo. This focus is reflected in its Next.js quickstart guide, which highlights minimal setup time. For backend integrations, Clerk provides SDKs for Node.js, Go, Ruby, and Python, allowing developers to verify user sessions and manage user data directly from their server-side applications. The platform is built to support multi-tenancy and organizational features, making it suitable for B2B SaaS applications that require complex user and organization management.

Security is a core component of Clerk's offering, with features like multi-factor authentication (MFA), passwordless options, and compliance certifications such as SOC 2 Type II, GDPR, and CCPA. The service manages sensitive user data in a secure, compliant manner, abstracting away many of the underlying security complexities from the application developer. This allows teams to focus on their core product features while relying on Clerk for user identity management.

Supported authentication methods

Clerk supports a range of authentication methods to accommodate diverse application requirements and user preferences. These methods are integrated into Clerk's pre-built UI components and can be configured through the Clerk Dashboard. The choice of method often depends on the desired user experience, security requirements, and application type.

Method When to Use Security Level
Email/Password Standard user accounts, widely understood. Moderate (can be enhanced with MFA)
OAuth (Social Logins) Quick sign-up/sign-in, reduces password fatigue. Integrates with providers like Google, GitHub, Facebook. High (delegates to trusted identity providers)
Magic Links (Email-based) Passwordless experience, convenient for users, reduces password management burden. Moderate (relies on email account security)
Passwordless (SMS/Phone) Mobile-first applications, quick access via phone number verification. Moderate (relies on phone number ownership)
Multi-Factor Authentication (MFA) Enhances security for any primary method by requiring a second verification factor (TOTP, SMS, backup codes). High (adds an extra layer of verification)
Single Sign-On (SSO) Enterprise applications, allows users to access multiple services with one set of credentials (often via SAML or OIDC). High (centralized identity management)

Clerk's pre-built UI components, such as <SignIn /> and <SignUp />, abstract the implementation details of these methods. Developers can configure which methods are enabled via the Clerk Dashboard, allowing for flexible authentication strategies. For example, an application might offer both email/password and social logins, with MFA enabled for all accounts to bolster security. The platform also supports advanced features like user impersonation, which can be useful for administrative tasks or customer support, allowing an authorized administrator to temporarily act as another user.

Getting your credentials

To integrate Clerk into an application, developers primarily need to obtain API keys and configure their application within the Clerk Dashboard. These credentials establish the link between the application and the Clerk service, enabling secure communication and user management.

1. Create a Clerk Application

The first step involves creating an application within the Clerk Dashboard. This process typically involves:

  • Navigating to the Clerk Dashboard.
  • Selecting or creating an instance.
  • Creating a new application, which will generate a set of API keys specific to that application.

2. Obtain API Keys

Clerk applications typically use two main types of keys:

  • Publishable Key (Frontend): This key is safe to expose in client-side code. It identifies your Clerk application and is used by Clerk's frontend SDKs and UI components to communicate with the Clerk backend. It is usually prefixed with pk_.
  • Secret Key (Backend): This key is sensitive and must be kept confidential on your server. It is used by Clerk's backend SDKs to perform privileged operations, such as verifying session tokens, managing users, or accessing sensitive data. It is usually prefixed with sk_.

These keys are found in the "API Keys" section of your application settings within the Clerk Dashboard. For detailed instructions on finding and using these keys, refer to Clerk's API Keys documentation.

3. Environment Configuration

Once obtained, the keys should be configured as environment variables in your application. This practice ensures that sensitive keys are not hardcoded directly into your codebase, improving security and maintainability. For example, in a Next.js application, you might configure them in a .env.local file:


NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY="pk_YOUR_PUBLISHABLE_KEY"
CLERK_SECRET_KEY="sk_YOUR_SECRET_KEY"

Clerk's SDKs are designed to automatically pick up these environment variables, simplifying the setup process. It's crucial to ensure that the secret key is never exposed to the client-side, typically by restricting its use to server-side code or API routes.

Authenticated request example

After a user successfully authenticates with Clerk, a session is established, and a session token (JWT) is issued. This token is typically stored in a secure cookie or local storage on the client side. When the client makes requests to a backend API that requires authentication, this token is included in the request headers.

Client-side with Clerk's SDKs

Clerk's frontend SDKs abstract much of the token management. For instance, in a React or Next.js application, you can use the useAuth hook to get the current session token:


import { useAuth } from '@clerk/nextjs';

function MyAuthenticatedComponent() {
  const { getToken } = useAuth();

  const fetchData = async () => {
    const token = await getToken(); // Gets the current session JWT
    if (token) {
      const response = await fetch('/api/my-protected-route', {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      const data = await response.json();
      console.log(data);
    }
  };

  return <button onClick={fetchData}>Fetch Protected Data</button>;
}

Backend verification

On the backend, your API must verify the authenticity and validity of the session token. Clerk provides backend SDKs for this purpose. The verification process typically involves:

  1. Receiving the JWT from the Authorization: Bearer <token> header.
  2. Using Clerk's SDK to verify the token's signature, expiration, and issuer.
  3. Extracting user information (e.g., user ID) from the verified token's payload for authorization checks.

Here's an example using Clerk's Node.js SDK (@clerk/nextjs/server for Next.js API routes or @clerk/clerk-sdk-node for generic Node.js):


// pages/api/my-protected-route.ts (Next.js API Route example)
import { getAuth } from '@clerk/nextjs/server';
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { userId } = getAuth(req); // Automatically verifies the session and extracts userId

  if (!userId) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  // User is authenticated, proceed with protected logic
  res.status(200).json({ message: `Hello, user ${userId}! This is protected data.` });
}

For more general Node.js applications, you would manually verify the token using @clerk/clerk-sdk-node's authenticateRequest function. This function handles the JWT verification against Clerk's public keys, ensuring that the token was issued by Clerk and has not been tampered with. This pattern aligns with standard OAuth 2.0 and OpenID Connect practices for token-based authentication, as described by the OAuth 2.0 framework documentation.

Security best practices

Implementing authentication requires adherence to security best practices to protect user data and prevent unauthorized access. Clerk provides features and guidelines to help developers maintain a secure environment.

1. Protect API Keys

  • Secret Keys: Never expose your Clerk Secret Key (sk_) on the client side. Store it as an environment variable and restrict its use to secure server-side environments or backend services.
  • Publishable Keys: While the Publishable Key (pk_) is designed for client-side use, ensure it's loaded securely, typically through environment variables during build time, to prevent accidental exposure in source control.

2. Implement Multi-Factor Authentication (MFA)

Enable MFA for all users or sensitive actions within your application. Clerk supports various MFA methods, including:

  • Time-based One-Time Passwords (TOTP) using authenticator apps.
  • SMS-based verification codes.
  • Backup codes for recovery.

MFA significantly reduces the risk of account compromise, even if primary credentials are leaked.

3. Secure Session Management

  • Short-lived Sessions: Configure appropriate session lifetimes to balance user convenience with security. Clerk allows customization of session token expiration.
  • Refresh Tokens: Understand how Clerk handles refresh tokens to maintain continuous user sessions securely without requiring frequent re-authentication.
  • Revocation: Implement mechanisms to revoke sessions when a user logs out, changes their password, or if suspicious activity is detected. Clerk's backend SDKs provide session management functions for this purpose.

4. Input Validation and Sanitization

Although Clerk handles much of the authentication logic, ensure that any user-provided data passed to your application's backend is properly validated and sanitized to prevent common web vulnerabilities like injection attacks.

5. Error Handling and Logging

Implement robust error handling for authentication failures. Avoid providing overly descriptive error messages that could aid attackers (e.g., "username not found" vs. "invalid credentials"). Log authentication attempts and failures for auditing and anomaly detection, but be careful not to log sensitive information like passwords or full tokens.

6. Keep SDKs and Dependencies Updated

Regularly update Clerk SDKs and other third-party dependencies to their latest versions. Updates often include security patches and improvements that address newly discovered vulnerabilities.

7. Compliance and Data Privacy

Leverage Clerk's compliance features (SOC 2 Type II, GDPR, CCPA) to ensure your application meets regulatory requirements for data privacy and security. Understand where user data is stored and how it is processed by Clerk to maintain compliance in your specific jurisdiction.

8. Protect Clerk Webhooks

If your application uses Clerk webhooks, ensure they are secured. Verify the signature of incoming webhooks to confirm they originate from Clerk and haven't been tampered with. This prevents malicious actors from sending forged events to your application.