Developer-friendly & type-safe Ruby SDK specifically catered to leverage clerk-sdk-ruby API.
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.
Clerk Backend API: The Clerk REST Backend API, meant to be accessed by backend servers.
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
Add this line to your application's Gemfile:
gem 'clerk-sdk-ruby', require: "clerk"And then execute:
$ bundle install
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 |
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
endThe 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
endapp/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include Clerk::Authenticatable
endFor API-only Rails apps:
class ApplicationController < ActionController::API
include Clerk::Authenticatable
endSkip the Railtie (for custom middleware setup):
export CLERK_SKIP_RAILTIE=truerequire '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
endconfig.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 MyAppIn 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 claimsThe 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
# ...
# }# 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# 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"]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
endReverification requires users to re-authenticate for sensitive operations.
| 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 |
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
endclass 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
enduse Clerk::Rack::Reverification,
preset: Clerk::StepUp::Preset::MODERATE,
routes: ['/settings/*', '/billing/*']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
endAvailable methods
- list - List all identifiers on the allow-list
- create - Add identifier to the allow-list
- delete - Delete identifier from allow-list
- create_api_key - Create an API Key
- get_api_keys - Get API Keys
- get_api_key - Get an API Key by ID
- update_api_key - Update an API Key
- delete_api_key - Delete an API Key
- get_api_key_secret - Get an API Key Secret
- revoke_api_key - Revoke an API Key
- verify_api_key - Verify an API Key
- update_instance_settings - Update instance settings
update_production_instance_domain- Update production instance domain⚠️ Deprecated
- list_plans - List all billing plans
- list_subscription_items - List all subscription items
- cancel_subscription_item - Cancel a subscription item
- extend_subscription_item_free_trial - Extend free trial for a subscription item
- create_price_transition - Create a price transition for a subscription item
- list_statements - List all billing statements
- get_statement - Retrieve a billing statement
- get_statement_payment_attempts - List payment attempts for a billing statement
- list - List all identifiers on the block-list
- create - Add identifier to the block-list
- delete - Delete identifier from block-list
- 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⚠️ Deprecatedget- Retrieve a template⚠️ Deprecatedrevert- Revert a template⚠️ Deprecatedtoggle_template_delivery- Toggle the delivery by Clerk for a template of a given type and slug⚠️ Deprecated
- get - Fetch the current instance
- update - Update instance settings
- update_restrictions - Update instance restrictions
- change_domain - Update production instance domain
- update_organization_settings - Update instance organization settings
- get_instance_protect - Get instance protect settings
- update_instance_protect - Update instance protect settings
- create - Create an invitation
- list - List all invitations
- bulk_create - Create multiple invitations
- revoke - Revokes an invitation
- 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
- create_token - Create a M2M Token
- list_tokens - Get M2M Tokens
- revoke_token - Revoke a M2M Token
- verify_token - Verify a M2M Token
- list - Get a list of machines for an instance
- create - Create a machine
- get - Retrieve a machine
- update - Update a machine
- delete - Delete a machine
- get_secret_key - Retrieve a machine secret key
- rotate_secret_key - Rotate a machine's secret key
- create_scope - Create a machine scope
- delete_scope - Delete a machine scope
- get_public_interstitial - Returns the markup for the interstitial page
- 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 role sets
- create - Create a role set
- get - Retrieve a role set
- update - Update a role set
- replace - Replace a role set
- add_roles - Add roles to a role set
- replace_role - Replace a role in a role set
- 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
- list - List all sessions
- create - Create a new active session
- get - Retrieve a session
- refresh - Refresh a session
- revoke - Revoke a session
- create_token - Create a session token
- create_token_from_template - Create a session token from a JWT template
preview- Preview changes to a template⚠️ Deprecated
- create - Retrieve a new testing token
- list - List all users
- create - Create a new user
- count - Count users
- get - Retrieve a user
- update - Update a user
- delete - Delete a user
- ban - Ban a user
- unban - Unban a user
- bulk_ban - Ban multiple users
- bulk_unban - Unban multiple users
- lock - Lock a user
- unlock - Unlock a user
- set_profile_image - Set user profile image
- delete_profile_image - Delete user profile image
- update_metadata - Merge and update a user's metadata
- get_billing_subscription - Retrieve a user's billing subscription
- get_o_auth_access_token - Retrieve the OAuth access token of a user
- get_organization_memberships - Retrieve all memberships for a user
- get_organization_invitations - Retrieve all invitations for a user
- verify_password - Verify the password of a user
- verify_totp - Verify a TOTP or backup code for a user
- disable_mfa - Disable a user's MFA methods
- delete_backup_codes - Disable all user's Backup codes
- delete_passkey - Delete a user passkey
- delete_web3_wallet - Delete a user web3 wallet
- delete_totp - Delete all the user's TOTPs
- delete_external_account - Delete External Account
- set_password_compromised - Set a user's password as compromised
- unset_password_compromised - Unset a user's password as compromised
- get_instance_organization_memberships - Get a list of all organization memberships within an instance.
- 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
- create_svix_app - Create a Svix app
- delete_svix_app - Delete a Svix app
- generate_svix_auth_url - Create a Svix Dashboard URL
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 | */* |
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
endrescue Clerk::AuthenticationError => e
puts e.status # HTTP status code
puts e.message
rescue Clerk::ConfigurationError => e
# Missing or invalid configuration
puts e.message
endbegin
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
endThis 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.
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.