loading
Preparing LoginRadius developer resources
Mission: Help enterprises accelerate digital transformation with our fully-managed Customer IAM technology.
Skip to main content

IO Scripts

The Script feature enables customers to define and execute custom code that responds to specific LoginRadius events, including user login, password reset, and other relevant actions. This code can be executed synchronously or asynchronously. This feature provides serverless computing capabilities integrated directly within the LoginRadius platform, enabling businesses to extend identity workflows without managing separate infrastructure.

Key Features

  • Custom Logic Execution: Trigger and run tailored code during specific events.
  • Synchronous and Asynchronous Execution: Choose between real-time execution or background processing based on workflow needs.
  • Third-Party Integration: Seamlessly interact with external APIs or services during specific events.
  • Security Enhancements: Implement additional validation or compliance checks during authentication flows.
  • Personalized User Experiences: Dynamically modify workflows based on user behavior or attributes.
  • Secure Execution: Scripts execute entirely within the LoginRadius backend and are not exposed to client-side environments, allowing safe handling of sensitive data such as API secrets or tokens.

This scripting capability offers greater flexibility and control, helping businesses create smarter, more adaptive CIAM solutions.

Key Things to Know Before You Start Writing a Script

Supported NPM Packages

When writing scripts, please use the set of supported npm packages to ensure optimal performance and compatibility within the scripting environment. These pre-approved modules are fully supported and thoroughly tested to ensure the smooth execution of your scripts:

  • underscore@1.13.6
  • axios@1.7.2
  • moment@2.30.1
  • async@3.2.5
  • @slack/webhook@7.0.2

The script must export a function named execute. Example:

exports.execute = async (lrObject, hook) => {
// Your logic here
};

Script Input Parameters

Your script will receive two parameters:

  1. lrObject: Contains all relevant data about the current event. Use this object to read inputs and understand the state of the operation.
    lrObject includes the following:
  • lrObject.Request: Provides details about the incoming request

    • IP

    • Language

    • UserAgent

  • lrObject.Identity: Provides identity details present in profile if user is authenticated, such as:

    • Email

    • PhoneId

    • UserName

    • EmailVerified

    • PhoneIdVerified

    • NoOfLogins

    • Uid

    • BirthDate

    • LastPasswordChangeDate

  • lrObject.Session.FormData: Contains all submitted form fields and their values for the current workflow node. Use this to access user input, e.g.:

    Example — reading a form field:

    const email = lrObject.Session.FormData["email"];

    Example — using form data in custom logic:

    exports.execute = async (lrObject, hook) => {
    const referralCode = lrObject.Session.FormData["referral_code"];
    if (referralCode) {
    hook.accessToken.setCustomClaim("referral_code", referralCode);
    }
    };

    Note: FormData is populated from any Page (form) node encountered in the workflow flow up to the point the script executes — not necessarily the immediately preceding node. Mandatory fields will always contain a value (the page enforces validation before submission). Optional fields may be null if the user left them empty — always check for null before using optional field values.

  • lrObject.IsAuthenticated: Indicates whether the user is currently authenticated. This is a boolean value (true or false).

    Example:

    if (lrObject.IsAuthenticated) {
    hook.accessToken.setCustomClaim("status", "authenticated");
    } else {
    hook.setError(401, "Unauthorized", "User is not authenticated.");
    }
  • const identities = lrObject?.Identity?.Identities;: To fetch social profile identities array in script use this code. Example Script:

exports.execute = async (lrObject, hook) => {
const identities = lrObject?.Identity?.Identities;
if (Array.isArray(identities) && identities.length > 0) {
const found = identities.some(identity => identity.Provider === "google");
if (!found) {
hook.setError(
146,
"Google login required",
"You must login with your Google account."
);
}
} else {
hook.setError(
147,
"No identities found1",
"No social identities are present for this user."
);
}
};

  1. hook: These are functions that allow you to modify or set access token claims, custom fields, and user metadata. Provides setter functions that allow you to update claims in the access token, custom fields, and metadata.

Methods Available in hook:

  1. hook.accessToken.setCustomClaim(claim, value):

    • Adds custom claims to the user's access token.
    • Both claim and value must be strings.
      Example: hook.accessToken.setCustomClaim("role", "admin");
  2. hook.identity.setCustomField(key, value):

    Sets custom fields for the user. The custom field should be present in the user’s profile.
    Example: hook.identity.setCustomField("LastLoginDate", new Date().toISOString());

  3. hook.identity.setMetaData(key, value):

    You can set metadata fields to manage user status and access. The following fields are available for use:

  • EmailVerified
  • IsLoginLocked
  • DisableLogin
  • IsActive

    Example: hook.identity.setMetaData("Region", "US");
  1. hook.idToken.setCustomClaim(key,value):

    Adds custom claims which will be reflected in the ID_token in OIDC flows.

    Example: hook.idToken.setCustomClaim('first_name', "mike")

    Note: There are few reserved claims that are restricted to be overwritten in id token like iss,iat,sub,nbf,exp.

  2. hook.setError(code, message, description):
    Sets an error with a specific code, message, and description.

    Example: hook.setError(400, "Invalid Email", "The email domain is not allowed.");

Accessing FormData in Scripts

We are exposing FormData in the script, making it accessible for custom logic and integrations.

To access the form data within your script, use:

const email = lrObject.Session.FormData["email"];

This will be a map containing the submitted form fields and their values. For example, to get the value of a field named email, use the code above.

Best Practices

  1. Always Validate Input:

    • Ensure that fields like lrObject.Identity.Email exist before accessing them to avoid runtime errors`.
  2. Handle Errors Gracefully:

    • Use hook.setError to handle validation or execution errors`.
  3. Avoid Blocking Modules:

    • The worker blocks certain Node.js modules—os (system info), fs (file system access), cluster (worker processes), and child_process (system commands)—for security reasons, as they access system-level resources.. Allowing such access could lead to unintended behavior, performance issues, or security vulnerabilities. To avoid such issues, do not attempt to use these modules in your script..
  4. Keep Scripts Simple:

    • Focus on a single responsibility per script to simplify debugging and maintenance.

Example:

Here is an example showing best practices by using error handling, ensuring function singularity, and avoiding blocked (system-level) modules

const axios = require("axios");

exports.execute = async (lrObject, hook) => {
try {
const response = await axios.get("https://api.example.com/user-data", {
params: { email: lrObject.Identity.Email },
});

if (response.data.isAdmin) {
hook.accessToken.setCustomClaim("role", "admin");
}
} catch (error) {
console.error("Error fetching user data:", error.message);
hook.setError(500, "Internal Server Error", "Failed to fetch user data.");
}
};

Common Use Cases for IO Scripts

IO Scripts are highly flexible and can be used for a variety of advanced identity and integration scenarios, including:

  • Complex Migration Strategies

    • Example: During user registration or login, check a third-party system (such as Azure AD, legacy database, or another IdP) to see if the user already exists before creating them in LoginRadius.
    • How: Use supported npm modules (like axios) to make API calls to external systems. Conditionally create or update users in LoginRadius based on the response.
  • Handling Different User Types

    • Example: Apply different logic for social users (with or without password), email/password users, or users with specific attributes.
    • How: Inspect lrObject.Identity and session data to determine user type, then branch logic accordingly. For example, skip password checks for social users, or enforce additional validation for email users.
  • Custom Claim Setup

    • Example: Add custom claims to the access token or ID token based on business logic, user profile, or external data.
    • How: Use hook.accessToken.setCustomClaim() and hook.idToken.setCustomClaim() to inject claims dynamically. This is useful for role-based access, feature flags, or compliance attributes.
  • Populating Custom Fields

    • Example: Automatically populate or update custom fields in the user profile during registration, login, or profile update flows.
    • How: Use hook.identity.setCustomField() to set or update custom fields based on form data, external API responses, or calculated values.
  • Enriching User Metadata

    • Example: Set metadata fields such as region, account status, or onboarding step.
    • How: Use hook.identity.setMetaData() to manage user metadata for downstream systems or analytics.
  • Error Handling and Validation

    • Example: Block registration for disposable email domains, or enforce business rules before allowing login.
    • How: Use hook.setError() to return custom error codes and messages, stopping the workflow if validation fails.

These use cases demonstrate the power and flexibility of IO Scripts for advanced identity orchestration, integration, and user management scenarios. Combine hooks, formData, and external API calls to build robust, adaptive workflows tailored to your business needs.