Skip to main content
The JavaScript SDK provides methods to connect users to third-party applications, manage configurations, and build custom integration experiences in your frontend. It gives you full control over the UI while handling OAuth flows, API key authentication, and configuration management.

When to Use

  • Build a fully custom integration UI matching your application design
  • Implement connection flows without pre-built components
  • Manage configurations programmatically in vanilla JavaScript or any framework
  • Need granular control over the user experience

Prerequisites

Before using the JavaScript SDK:
  1. Create a Linked Account for your user using the Node.js SDK or API
  2. Generate a Session Token using the Node.js SDK or API
Session tokens expire after 24 hours. Generate a new token for each user session.

Installation

Install the SDK using npm or include it directly in your browser.
npm install --save @refoldai/refold-js
Upgrading from @cobaltio/cobalt-js? The JavaScript SDK has been renamed to @refoldai/refold-js (now major version 10). To upgrade:
  • Install the new package and remove the old one: npm install @refoldai/refold-js
  • Update imports: import { Cobalt } from "@cobaltio/cobalt-js" becomes import { Refold } from "@refoldai/refold-js"
  • Rename the client: new Cobalt(...) becomes new Refold(...)
See the package on npm and the JavaScript SDK reference for full method docs and any other changes in v10.

Initialization

Import and initialize the SDK with your session token.
import { Refold } from "@refoldai/refold-js";

const refold = new Refold({
  token: "YOUR_SESSION_TOKEN"
});

Methods

Returns application details for enabled applications. Use this to display available integrations to your users.
slug
string
Application identifier. Omit to retrieve all enabled applications.
Returns: Promise<Application | Application[]>
const apps = await refold.getApp();
console.log(apps);
// Returns array of all enabled applications
Example Response:
{
  "name": "Slack",
  "icon": "https://cobalt-app-logos.s3.ap-south-1.amazonaws.com/slack/logo.png",
  "description": "Slack is a platform for team communication...",
  "auth_type": "oauth2",
  "type": "slack",
  "app_id": "64c357c739ec788238ab5f95",
  "tags": ["Communication"],
  "version": {
    "_v": "1.0.0",
    "description": "Slack is a platform for team communication..."
  },
  "slug": "slack",
  "reauth_required": false
}
Use Case: Build an integrations catalog page showing all available applications.
// Display integration cards
const apps = await refold.getApp();

apps.forEach(app => {
  console.log(`${app.name} - ${app.auth_type}`);
  // Render integration card with app.icon, app.name, app.description
});
Initiates the authentication flow for an application. For OAuth apps, opens a popup window. For API key apps, saves the provided credentials.
slug
string
required
Application identifier (e.g., slack, hubspot).
payload
object
Authentication credentials for API key-based applications. Not required for OAuth apps.
Returns: Promise<boolean> - true if connection succeeds
// Opens OAuth popup for user authorization
const success = await refold.connect("slack");

if (success) {
  console.log("Slack connected successfully");
}
For OAuth applications, the SDK handles the entire OAuth flow including popup management and token exchange.
Use Case: Add a “Connect” button to each integration card.
async function handleConnect(appSlug, authType) {
  try {
    if (authType === "oauth2") {
      await refold.connect(appSlug);
    } else {
      // Show form for API credentials
      const credentials = await showCredentialsForm(appSlug);
      await refold.connect(appSlug, credentials);
    }
    showSuccessMessage(`${appSlug} connected!`);
  } catch (error) {
    showErrorMessage(`Connection failed: ${error.message}`);
  }
}
Disconnects an application and removes all associated data including credentials and configurations.
slug
string
required
Application identifier to disconnect.
Returns: Promise<boolean> - true if disconnection succeeds
await refold.disconnect("slack");
console.log("Slack disconnected");
This action is irreversible. All configurations and credentials for the application are permanently deleted.
Use Case: Add a “Disconnect” option in your integration settings.
async function handleDisconnect(appSlug) {
  const confirmed = await showConfirmDialog(
    `Disconnect ${appSlug}? All settings will be lost.`
  );
  
  if (confirmed) {
    await refold.disconnect(appSlug);
    refreshIntegrationList();
  }
}
Retrieves or creates a configuration for the linked account. Returns available workflows, settings fields, and current values.
options
object
required
Configuration options.
options.slug
string
required
Application identifier.
options.config_id
string
Unique identifier for this configuration. Defaults to linked_account_id if not provided.
options.labels
object
Dynamic labels for field mapping. Used with map-type fields.
Returns: Promise<ConfigResponse>
const config = await refold.config({
  slug: "slack",
  config_id: "config_123",
  labels: {}
});

console.log(config);
Example Response:
{
  "slug": "slack",
  "config_id": "config_123",
  "fields": [
    {
      "required": false,
      "id": "64da0b57c9ae95561bb0a24d",
      "name": "Channel",
      "field_type": "select",
      "options": [
        { "name": "general", "value": "C044U7Q074J" },
        { "name": "random", "value": "C044U7Q074K" }
      ],
      "labels": []
    }
  ],
  "workflows": [
    {
      "id": "64d1fac58716dc5065127ffe",
      "name": "Send message in a channel",
      "description": "",
      "enabled": false,
      "fields": [
        {
          "required": false,
          "id": "64da0b57c9ae95561bb0a24f",
          "name": "Channel",
          "field_type": "select",
          "options": [
            { "name": "general", "value": "C044U7Q074J" }
          ],
          "labels": []
        }
      ]
    }
  ],
  "field_errors": []
}
Use Case: Build a settings page for users to configure their integration.
async function loadConfigurationPage(appSlug) {
  const config = await refold.config({ slug: appSlug });
  
  // Render global settings fields
  config.fields.forEach(field => {
    renderField(field);
  });
  
  // Render workflow toggles and settings
  config.workflows.forEach(workflow => {
    renderWorkflowToggle(workflow);
  });
}
Updates configuration values including field settings and workflow states.
payload
object
required
Configuration update payload.
payload.slug
string
required
Application identifier.
payload.config_id
string
Configuration identifier.
payload.fields
object
Map of field IDs to their values.
payload.workflows
array
Array of workflow configurations.
payload.workflows[].id
string
required
Workflow identifier.
payload.workflows[].enabled
boolean
required
Enable or disable the workflow.
payload.workflows[].fields
object
Map of workflow field IDs to their values.
Returns: Promise<ConfigResponse> - Updated configuration
const updatedConfig = await refold.updateConfig({
  slug: "slack",
  config_id: "config_123",
  fields: {
    "64da0b57c9ae95561bb0a24d": "C044U7Q074J"  // Set channel
  },
  workflows: [
    {
      id: "64d1fac58716dc5065127ffe",
      enabled: true,
      fields: {
        "64da0b57c9ae95561bb0a24f": "C044U7Q074J"
      }
    }
  ]
});
Use Case: Save user configuration changes.
async function saveConfiguration(appSlug, configId, formData) {
  try {
    await refold.updateConfig({
      slug: appSlug,
      config_id: configId,
      fields: formData.globalFields,
      workflows: formData.workflows.map(w => ({
        id: w.id,
        enabled: w.enabled,
        fields: w.fieldValues
      }))
    });
    showSuccessMessage("Configuration saved!");
  } catch (error) {
    showErrorMessage(`Save failed: ${error.message}`);
  }
}
Deletes a configuration for the specified application.
slug
string
required
Application identifier.
configId
string
Configuration identifier to delete.
Returns: Promise<void>
await refold.deleteConfig("slack", "config_123");
console.log("Configuration deleted");
This permanently deletes all configuration settings for the application.

Complete Example

This example demonstrates a full integration page with connection management and configuration.
import { Refold } from "@refoldai/refold-js";

class IntegrationManager {
  constructor(sessionToken) {
    this.refold = new Refold({ token: sessionToken });
  }

  async loadIntegrations() {
    // Get all enabled applications
    const apps = await this.refold.getApp();
    return apps;
  }

  async connectApp(slug, credentials = null) {
    try {
      if (credentials) {
        // API key authentication
        return await this.refold.connect(slug, credentials);
      } else {
        // OAuth authentication
        return await this.refold.connect(slug);
      }
    } catch (error) {
      console.error(`Failed to connect ${slug}:`, error);
      throw error;
    }
  }

  async disconnectApp(slug) {
    return await this.refold.disconnect(slug);
  }

  async getConfig(slug, configId) {
    return await this.refold.config({
      slug,
      config_id: configId
    });
  }

  async saveConfig(slug, configId, fields, workflows) {
    return await this.refold.updateConfig({
      slug,
      config_id: configId,
      fields,
      workflows
    });
  }
}

// Usage
async function initializeIntegrationPage(sessionToken) {
  const manager = new IntegrationManager(sessionToken);
  
  // Load and display available integrations
  const apps = await manager.loadIntegrations();
  
  apps.forEach(app => {
    // Render integration card
    const card = createIntegrationCard(app);
    
    // Add connect handler
    card.querySelector('.connect-btn').onclick = async () => {
      await manager.connectApp(app.slug);
      refreshUI();
    };
    
    // Add configure handler
    card.querySelector('.configure-btn').onclick = async () => {
      const config = await manager.getConfig(app.slug, 'default');
      showConfigModal(config);
    };
    
    document.getElementById('integrations').appendChild(card);
  });
}

Troubleshooting

ProblemSolution
”Invalid token” errorGenerate a new session token. Tokens expire after 24 hours.
Token not working after page refreshStore the token and reinitialize the SDK on page load, or fetch a new token from your backend.
OAuth popup blockedEnsure .connect() is called in response to a user action (click). Browsers block popups not triggered by user interaction.
ProblemSolution
OAuth popup closes without completingCheck browser popup settings. Ensure your domain is whitelisted in the Refold dashboard.
API key connection failsVerify credentials are correct. Check the application’s required fields in the dashboard.
reauth_required: true in responseThe user’s credentials have expired. Call .connect() again to re-authenticate.
ProblemSolution
Field options not loadingEnsure the user is connected to the application before calling .config().
field_errors in config responseCheck that all required fields have valid values. Review the error messages for specific issues.
Workflow not triggeringVerify enabled: true is set in the workflow configuration.

What’s Next