Skip to content

Access the Clerk Backend API from Ruby

Notifications You must be signed in to change notification settings

clerk/clerk-sdk-ruby

Repository files navigation

clerk-sdk-ruby

Developer-friendly & type-safe Ruby SDK specifically catered to leverage clerk-sdk-ruby API.

Built by Speakeasy License: MIT



Important

This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your workspace. Delete this section before > publishing to a package manager.

Summary

Clerk Backend API: The Clerk REST Backend API, meant to be accessed by backend servers.

Versions

When the API changes in a way that isn't compatible with older versions, a new version is released. Each version is identified by its release date, e.g. 2025-04-10. For more information, please see Clerk API Versions.

Please see https://clerk.com/docs for more information.

More information about the API can be found at https://clerk.com/docs

Table of Contents

SDK Installation

Add this line to your application's Gemfile:

gem 'clerk-sdk-ruby', require: "clerk"

And then execute:

$ bundle install

Configuration

Environment Variables

The SDK automatically reads these environment variables:

Variable Description
CLERK_SECRET_KEY Your Clerk secret key (starts with sk_)
CLERK_PUBLISHABLE_KEY Your Clerk publishable key (starts with pk_)
CLERK_SIGN_IN_URL to redirect unauthenticated users
CLERK_SIGN_UP_URL for new user registration
CLERK_SIGN_OUT_URL URL for sign out

Programmatic Configuration

require 'clerk'

Clerk.configure do |config|
  # Optional: Override environment variables
  config.publishable_key = ENV['CLERK_PUBLISHABLE_KEY']
  config.secret_key = ENV['CLERK_SECRET_KEY']
  
  # Enable debug logging
  config.debug = true
  config.logger = Logger.new($stdout)
  
  # Exclude routes from authentication middleware
  config.excluded_routes = ['/health', '/public/*']
  
  # Custom cache store (defaults to Rails.cache or ActiveSupport::Cache::MemoryStore)
  config.cache_store = Rails.cache
end

Framework Integration

Rails

The SDK automatically integrates with Rails via a Railtie. Simply include Clerk::Authenticatable in your controllers:

config/initializers/clerk.rb

Clerk.configure do |config|
  # Configuration options here
end

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base 
  include Clerk::Authenticatable
end

For API-only Rails apps:

class ApplicationController < ActionController::API
  include Clerk::Authenticatable
end

Skip the Railtie (for custom middleware setup):

export CLERK_SKIP_RAILTIE=true

Sinatra

require 'clerk/sinatra'
require 'sinatra/base'

class App < Sinatra::Base
  register Sinatra::Clerk
  
  get '/' do
    if clerk.user?
      "Hello, #{clerk.user.first_name}!"
    else
      "Please sign in"
    end
  end
  
  # Require authentication for specific routes
  get '/dashboard', auth: true do
    erb :dashboard
  end
  
  # Require reverification for sensitive routes
  get '/settings', reverify: true do
    erb :settings
  end
end

Rack

config.ru

require 'clerk/rack'

use Clerk::Rack::Middleware

# Optional: Add reverification middleware
use Clerk::Rack::Reverification,
    preset: Clerk::StepUp::Preset::STRICT,
    routes: ['/admin/*', '/settings/*']

run MyApp

Authentication & Session Management

Accessing the Clerk Helper

In all frameworks, the clerk helper provides access to authentication state:

# Check if user is authenticated
clerk.user?  # => true/false

# Get current user (makes API call, cached for 60 seconds)
clerk.user   # => Clerk::Models::User or nil

# Get user ID without API call
clerk.user_id  # => "user_abc123" or nil

# Get session claims (JWT payload)
clerk.session  # => Hash with JWT claims

Session Claims

The session contains JWT claims including:

clerk.session
# {
#   "sub" => "user_abc123",           # User ID
#   "sid" => "sess_xyz789",           # Session ID
#   "org_id" => "org_123",            # Organization ID (if applicable)
#   "org_slug" => "my-org",           # Organization slug
#   "org_role" => "org:admin",        # Organization role
#   "org_permissions" => [...],       # Organization permissions
#   "iat" => 1234567890,              # Issued at
#   "exp" => 1234571490,              # Expiration
#   ...
# }

Accessing User & Organization Data

# Get full user object (API call, cached)
user = clerk.user

# Access user properties
user.id                  # => "user_abc123"
user.first_name          # => "John"
user.last_name           # => "Doe"
user.email_addresses     # => Array of email addresses
user.primary_email_address_id
user.phone_numbers
user.created_at
user.updated_at
user.public_metadata
user.private_metadata

Organization Information

# Check if user is in an organization context
clerk.organization?  # => true/false

# Get organization ID
clerk.organization_id  # => "org_123" or nil

# Get full organization object (API call, cached)
org = clerk.organization

# Access organization properties
org.id
org.name
org.slug
org.members_count

# Get user's role in the organization
clerk.organization_role  # => "org:admin"

# Get user's permissions
clerk.organization_permissions  # => ["org:billing:manage", "org:users:read"]

Backend API Operations

require 'clerk'

# Initialize the SDK
sdk = Clerk::SDK.new

# Or with explicit credentials
sdk = Clerk::SDK.new(secret_key: 'sk_test_...')

# List users
response = sdk.users.list(limit: 10, offset: 0)
response.user_list.each do |user|
  puts user.email_addresses.first.email_address
end

Step-Up Verification (Reverification)

Reverification requires users to re-authenticate for sensitive operations.

Presets

Preset Timeout Level
Clerk::StepUp::Preset::STRICT 10 minutes Second factor
Clerk::StepUp::Preset::STRICT_MFA 10 minutes Multi-factor
Clerk::StepUp::Preset::MODERATE 60 minutes Second factor
Clerk::StepUp::Preset::LAX 24 hours Second factor

Rails Usage

class SettingsController < ApplicationController
  before_action :require_reverification!, only: [:update_password]
  
  def update_password
    # Only reached if reverification passed
  end
  
  # Or with custom preset
  def delete_account
    require_reverification!(Clerk::StepUp::Preset::STRICT_MFA) do |preset|
      # Custom handling when reverification is needed
      render json: { error: 'Please re-authenticate' }, status: 403
    end
  end
end

Sinatra Usage

class App < Sinatra::Base
  register Sinatra::Clerk
  
  before '/admin/*' do
    require_reverification!(Clerk::StepUp::Preset::STRICT)
  end
  
  # Or using route condition
  post '/delete-account', reverify: Clerk::StepUp::Preset::STRICT_MFA do
    # Handle deletion
  end
end

Rack Middleware

use Clerk::Rack::Reverification,
    preset: Clerk::StepUp::Preset::MODERATE,
    routes: ['/settings/*', '/billing/*']

Manual Check

if clerk.user_needs_reverification?(Clerk::StepUp::Preset::STRICT)
  # User needs to re-authenticate
end

# Check if user has passed reverification
if clerk.user_reverified?(level: :second_factor, after_minutes: 10)
  # User has recently verified
end

Available Resources and Operations

Available methods
  • list - List all identifiers on the allow-list
  • create - Add identifier to the allow-list
  • delete - Delete identifier from allow-list
  • list - List all identifiers on the block-list
  • create - Add identifier to the block-list
  • delete - Delete identifier from block-list
  • list - List all clients ⚠️ Deprecated
  • verify - Verify a client
  • get - Get a client
  • list - List all instance domains
  • add - Add a domain
  • delete - Delete a satellite domain
  • update - Update a domain
  • create - Create an email address
  • get - Retrieve an email address
  • delete - Delete an email address
  • update - Update an email address
  • upsert - Update a template for a given type and slug ⚠️ Deprecated
  • list - List all templates ⚠️ Deprecated
  • get - Retrieve a template ⚠️ Deprecated
  • revert - Revert a template ⚠️ Deprecated
  • toggle_template_delivery - Toggle the delivery by Clerk for a template of a given type and slug ⚠️ Deprecated
  • get_jwks - Retrieve the JSON Web Key Set of the instance
  • list - List all templates
  • create - Create a JWT template
  • get - Retrieve a template
  • update - Update a JWT template
  • delete - Delete a Template
  • verify - Verify an OAuth Access Token
  • list - Get a list of OAuth applications for an instance
  • create - Create an OAuth application
  • get - Retrieve an OAuth application by ID
  • update - Update an OAuth application
  • delete - Delete an OAuth application
  • rotate_secret - Rotate the client secret of the given OAuth application
  • create - Create a new organization domain.
  • list - Get a list of all domains of an organization.
  • update - Update an organization domain.
  • delete - Remove a domain from an organization.
  • list_all - List all organization domains
  • get_all - Get a list of organization invitations for the current instance
  • create - Create and send an organization invitation
  • list - Get a list of organization invitations
  • bulk_create - Bulk create and send organization invitations
  • list_pending - Get a list of pending organization invitations ⚠️ Deprecated
  • get - Retrieve an organization invitation by ID
  • revoke - Revoke a pending organization invitation
  • create - Create a new organization membership
  • list - Get a list of all members of an organization
  • update - Update an organization membership
  • delete - Remove a member from an organization
  • update_metadata - Merge and update organization membership metadata
  • list - Get a list of all organization permissions
  • create - Create a new organization permission
  • get - Get an organization permission
  • update - Update an organization permission
  • delete - Delete an organization permission
  • list - Get a list of organization roles
  • create - Create an organization role
  • get - Retrieve an organization role
  • update - Update an organization role
  • delete - Delete an organization role
  • assign_permission - Assign a permission to an organization role
  • remove_permission - Remove a permission from an organization role
  • list - Get a list of organizations for an instance
  • create - Create an organization
  • get - Retrieve an organization by ID or slug
  • update - Update an organization
  • delete - Delete an organization
  • merge_metadata - Merge and update metadata for an organization
  • upload_logo - Upload a logo for the organization
  • delete_logo - Delete the organization's logo.
  • get_billing_subscription - Retrieve an organization's billing subscription
  • create - Create a phone number
  • get - Retrieve a phone number
  • delete - Delete a phone number
  • update - Update a phone number
  • verify - Verify the proxy configuration for your domain
  • list - List all redirect URLs
  • create - Create a redirect URL
  • get - Retrieve a redirect URL
  • delete - Delete a redirect URL
  • list - Get a list of SAML Connections for an instance
  • create - Create a SAML Connection
  • get - Retrieve a SAML Connection by ID
  • update - Update a SAML Connection
  • delete - Delete a SAML Connection
  • create - Create sign-in token
  • revoke - Revoke the given sign-in token
  • get - Retrieve a sign-up by ID
  • update - Update a sign-up
  • preview - Preview changes to a template ⚠️ Deprecated
  • create - Retrieve a new testing token
  • list - List all waitlist entries
  • create - Create a waitlist entry
  • delete - Delete a pending waitlist entry
  • invite - Invite a waitlist entry
  • reject - Reject a waitlist entry

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an error.

By default an API error will raise a Errors::APIError, which has the following properties:

Property Type Description
message string The error message
status_code int The HTTP status code
raw_response Faraday::Response The raw HTTP response
body string The response content

When custom error responses are specified for an operation, the SDK may also throw their associated exception. You can refer to respective Errors tables in SDK docs for more details on possible exception types for each operation. For example, the verify method throws the following exceptions:

Error Type Status Code Content Type
Models::Errors::ClerkErrors 400, 401, 404 application/json
Errors::APIError 4XX, 5XX */*

Example

API Errors

begin
  response = sdk.users.get(user_id: 'invalid')
rescue Clerk::Models::Errors::ClerkErrors => e
  # Clerk-specific errors (400, 401, 404)
  puts e.message
  puts e.raw_response.status
rescue Clerk::Errors::APIError => e
  # General API errors
  puts e.status_code
  puts e.body
end

Authentication Errors

rescue Clerk::AuthenticationError => e
  puts e.status  # HTTP status code
  puts e.message
rescue Clerk::ConfigurationError => e
  # Missing or invalid configuration
  puts e.message
end

JWT Errors

begin
  claims = sdk.verify_token(token)
rescue JWT::ExpiredSignature
  # Token has expired
rescue JWT::InvalidIatError
  # Token not yet active
rescue JWT::DecodeError
  # Malformed or invalid token
end

Development

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.

SDK Created by Speakeasy