Developer Integration Guide

Seamlessly integrate CORS management into your web application with our powerful npm package. Enable, disable, and monitor cross-origin requests with just a few lines of code.

Getting Started

Transform your web development experience with the cors-unlocker npm package. Designed for developers who need reliable CORS management without the complexity.

GitHub ActionsTypeScriptnpm versionnpm downloads

Quick Installation

Get up and running in seconds with your preferred package manager:

# Using npm
npm install cors-unlocker

# Using yarn
yarn add cors-unlocker

# Using pnpm
pnpm add cors-unlocker

How It Works

The cors-unlocker package provides a seamless bridge between your web application and the CORS Unlocker browser extension. Here’s the magic behind it:

πŸ“

Secure Communication: Our package communicates with the browser extension through a secure iframe bridge, ensuring your website’s integrity while providing powerful CORS management capabilities.

When CORS is enabled, the extension intelligently modifies HTTP responses by adding the necessary Access-Control-Allow-Origin headers, making cross-origin requests possible without server-side changes.

Core API Reference

Extension Detection

appCors.isExtInstalled()

Check if the CORS Unlocker extension is available

Returns

Promise<boolean>

Example

import appCors from 'cors-unlocker';

// Check if the extension is installed
const isInstalled = await appCors.isExtInstalled()
console.log('Extension available:', isInstalled)

CORS Status Management

appCors.isEnabled()

Monitor and control CORS settings with precision

Returns

Promise<{ enabled: boolean, credentials: boolean } | false>

Example

// Check current CORS status
try {
  const status = await appCors.isEnabled()
  console.log('CORS status:', status)
  // Returns: { enabled: boolean, credentials: boolean } or false
} catch (error) {
  console.error('Extension not available:', error)
}

Enable CORS Protection

appCors.enable(options?)

Activate CORS with optional credential support. May require user confirmation and has no timeout limit to ensure reliable operation.

Parameters

credentials boolean

Enable credential-based requests (uses extension default if not specified)

reason string

Description for user consent

Returns

Promise<{ enabled: boolean, credentials: boolean }>

Example

// Basic CORS activation (uses default credentials setting)
const status = await appCors.enable()
console.log('CORS enabled:', status.enabled, 'Credentials:', status.credentials)

// Enable with explicit credentials for authenticated requests
const authStatus = await appCors.enable({
  credentials: true,
  reason: 'Testing authenticated API endpoints'
})
console.log('Auth enabled:', authStatus.credentials)

Disable CORS Protection

appCors.disable()

Safely disable CORS when no longer needed

Returns

Promise<void>

Example

try {
  await appCors.disable()
  console.log('CORS protection disabled')
} catch (error) {
  console.error('Failed to disable CORS:', error)
}

Extension Management

Quick access to extension settings and installation:

// Open extension settings
await appCors.openExtOptions()

// Direct users to extension store
appCors.openStorePage()

Advanced Usage Patterns

Error Handling Best Practices

import appCors, { AppCorsError } from 'cors-unlocker'

try {
  await appCors.enable({ credentials: true })
} catch (error) {
  if (error instanceof AppCorsError) {
    switch (error.type) {
      case 'not-installed':
        // Guide user to install extension
        appCors.openStorePage()
        break
      case 'user-cancel':
        // User declined the request
        console.log('User cancelled CORS activation')
        break
      default:
        console.error('CORS error:', error.message)
    }
  }
}

React Integration Example

import { useState, useEffect } from 'react'
import appCors from 'cors-unlocker'

function CORSManager() {
  const [corsStatus, setCorsStatus] = useState(null)
  const [isInstalled, setIsInstalled] = useState(false)

  useEffect(() => {
    // Check installation status
    appCors.isExtInstalled().then(setIsInstalled)
    
    // Check initial CORS status
    appCors.isEnabled().then(setCorsStatus)
  }, [])

  const toggleCORS = async () => {
    try {
      if (corsStatus?.enabled) {
        await appCors.disable()
        // After disable, check the current status
        setCorsStatus(await appCors.isEnabled())
      } else {
        const newStatus = await appCors.enable({ credentials: true })
        setCorsStatus(newStatus)
      }
    } catch (error) {
      console.error('Failed to toggle CORS:', error)
    }
  }

  if (!isInstalled) {
    return (
      <button onClick={() => appCors.openStorePage()}>
        Install CORS Unlocker
      </button>
    )
  }

  return (
    <button onClick={toggleCORS}>
      {corsStatus?.enabled ? 'Disable' : 'Enable'} CORS
    </button>
  )
}

Real-World Integration Patterns

Pattern 1: Progressive Enhancement for Internal Tools

Many developers use CORS Unlocker to enhance internal company tools without requiring server-side changes:

import appCors from 'cors-unlocker'

class APIIntegration {
  private corsEnabled = false
  
  async init() {
    try {
      const isInstalled = await appCors.isExtInstalled()
      if (isInstalled) {
        await appCors.enable({
          reason: 'Enable direct API access for company dashboard'
        })
        this.corsEnabled = true
        console.log('βœ… Direct API access enabled')
      } else {
        console.log('πŸ“¦ Extension not installed, using proxy fallback')
      }
    } catch (error) {
      console.log('⚠️ CORS unavailable, using proxy fallback')
    }
  }
  
  async fetchData(endpoint: string) {
    const url = this.corsEnabled 
      ? `https://api.company.com${endpoint}`
      : `/api/proxy${endpoint}` // Fallback to server proxy
      
    return fetch(url)
  }
}

Pattern 2: Development vs Production Configuration

Smart handling of different environments:

const config = {
  development: {
    useDirectAPI: true,
    fallbackToProxy: false
  },
  production: {
    useDirectAPI: false, // Force proxy in production
    fallbackToProxy: true
  }
}

async function setupAPIClient() {
  const env = process.env.NODE_ENV
  const { useDirectAPI, fallbackToProxy } = config[env] || config.development
  
  if (useDirectAPI) {
    const canUseCORS = await appCors.isExtInstalled()
    if (canUseCORS) {
      await appCors.enable()
      return new DirectAPIClient()
    }
  }
  
  if (fallbackToProxy) {
    return new ProxyAPIClient()
  }
  
  throw new Error('No API access method available')
}

Pattern 3: User-Friendly Installation Flow

Guide users through extension installation with a smooth UX:

class CORSManager {
  async requestAccess() {
    const isInstalled = await appCors.isExtInstalled()
    
    if (!isInstalled) {
      const userWantsToInstall = await this.showInstallationDialog()
      if (userWantsToInstall) {
        appCors.openStorePage()
        // Listen for extension installation
        return this.waitForInstallation()
      }
      return false
    }
    
    try {
      await appCors.enable({
        reason: 'Access external APIs for enhanced features'
      })
      return true
    } catch (error) {
      if (error.type === 'user-cancel') {
        this.showWhyNeededDialog()
      }
      return false
    }
  }
  
  private async waitForInstallation(): Promise<boolean> {
    return new Promise((resolve) => {
      const checkInterval = setInterval(async () => {
        const isInstalled = await appCors.isExtInstalled()
        if (isInstalled) {
          clearInterval(checkInterval)
          resolve(true)
        }
      }, 1000)
      
      // Timeout after 5 minutes
      setTimeout(() => {
        clearInterval(checkInterval)
        resolve(false)
      }, 5 * 60 * 1000)
    })
  }
}

Common Use Cases & Implementation Tips

Internal Company Dashboards

Scenario: Building a dashboard that aggregates data from multiple SaaS tools (Slack, GitHub, Jira, etc.)

Implementation Strategy:

  • Use CORS Unlocker for development and internal deployment
  • Implement graceful fallback to server-side proxy for external users
  • Cache responses to minimize API calls
// Dashboard API aggregator
class DashboardAPI {
  private apis = {
    github: 'https://api.github.com',
    slack: 'https://slack.com/api',
    jira: 'https://company.atlassian.net/rest/api/3'
  }
  
  async aggregateData() {
    await appCors.enable()
    
    const [githubData, slackData, jiraData] = await Promise.all([
      this.fetchGitHub(),
      this.fetchSlack(),
      this.fetchJira()
    ])
    
    return { github: githubData, slack: slackData, jira: jiraData }
  }
}

Rapid API Prototyping

Scenario: Testing integrations with third-party APIs during development

Benefits:

  • No backend setup required
  • Test API responses immediately
  • Iterate faster on frontend logic
// Quick API testing setup
async function testAPIIntegration() {
  await appCors.enable({ 
    reason: 'Testing API integration for prototype' 
  })
  
  // Test multiple endpoints quickly
  const apis = [
    'https://jsonplaceholder.typicode.com/posts',
    'https://api.github.com/repos/microsoft/vscode',
    'https://httpbin.org/json'
  ]
  
  for (const api of apis) {
    try {
      const response = await fetch(api)
      const data = await response.json()
      console.log(`βœ… ${api}:`, data)
    } catch (error) {
      console.log(`❌ ${api}:`, error.message)
    }
  }
}

MVP and Startup Applications

Scenario: Building an MVP that needs to integrate with external APIs without backend infrastructure

Cost Savings:

  • $0 proxy server costs
  • Faster time to market
  • Focus budget on core features
// MVP startup integration
class MVPApp {
  async initializeExternalServices() {
    const corsAvailable = await appCors.isExtInstalled()
    
    if (!corsAvailable) {
      // Show value proposition to users
      this.showExtensionBenefits()
      return
    }
    
    await appCors.enable({
      reason: 'Enable seamless integration with your favorite tools'
    })
    
    // Now can integrate with any API directly
    this.enableFeatures(['analytics', 'notifications', 'dataimport'])
  }
  
  showExtensionBenefits() {
    // Modal explaining how extension enables enhanced features
    // without requiring them to trust a third-party proxy server
  }
}

Browser Compatibility

Supported Browsers

🌐

Chrome 88+ Popular

Full support with Manifest V3

🦊

Firefox 85+ Stable

WebExtensions API support

🧭

Safari 14+ New

Safari Web Extensions

πŸ’Ž

Edge 88+ Chromium

Chromium-based support

Support & Community

Get Help & Connect

πŸ“š

Documentation

Complete API reference and guides

View Docs β†’
πŸ›

Report Issues

Found a bug or have suggestions?

GitHub Issues β†’
πŸ’¬

Discussions

Community support and ideas

Join Discussion β†’
πŸš€

Try Playground

Test CORS functionality live

Open Playground β†’

Built with ❀️ for developers who need reliable CORS management

Support Our Work

CORS Unlocker is completely free and open source. If it saves you time and makes your development easier, consider supporting our continued development!

Show Your Appreciation

Help us keep this tool free and continuously improving