@edge-markets/connect-link

中文文档
3.0.0发布于 2026/10/27MITTypeScriptESM + CJS近 30 天下载 1.6万

Browser SDK for EDGE Connect popup authentication

原始使用文档
文档目录18 节
  1. Features
  2. Installation
  3. Quick Start
  4. ⚠️ Important: User Gesture Requirement
  5. Configuration
  6. Callbacks
  7. onSuccess
  8. onExit
  9. onEvent
  10. Methods
  11. Scopes
  12. React Hook
  13. Hook Return Values
  14. Manual React Example
  15. How It Works
  16. Security
  17. Related Packages
  18. License

@edge-markets/connect-link

Browser SDK for EDGE Connect popup authentication.

Features

  • 🔒 Secure by default - PKCE OAuth flow, no client secret in browser
  • 🚀 Simple API - Just new EdgeLink() and link.open()
  • 📱 Works everywhere - Handles popup blockers gracefully
  • 📊 Event tracking - onSuccess, onExit, onEvent callbacks
  • 🎨 Beautiful loading state - Professional branded experience
  • 📝 Full TypeScript - Complete type definitions

Installation

npm install @edge-markets/connect-link
# or
pnpm add @edge-markets/connect-link
# or
yarn add @edge-markets/connect-link

Quick Start

import { EdgeLink } from '@edge-markets/connect-link'

// 1. Create instance (do this once)
const link = new EdgeLink({
  clientId: 'your-client-id',
  environment: 'sandbox',
  onSuccess: (result) => {
    // Send to your backend for token exchange
    fetch('/api/edge/exchange', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        code: result.code,
        codeVerifier: result.codeVerifier,
      }),
    })
  },
  onExit: (metadata) => {
    if (metadata.reason === 'popup_blocked') {
      alert('Please allow popups for this site')
    }
  },
})

// 2. Open from a click handler
document.getElementById('connect-btn')!.onclick = () => link.open()

⚠️ Important: User Gesture Requirement

link.open() MUST be called directly from a user click handler!

Browsers block popups that aren't triggered by user interaction. Any async work before calling open() will break this.

// ✅ Correct - direct click handler
button.onclick = () => link.open()

// ✅ Correct - immediate call in handler
button.onclick = () => {
  trackClick() // sync ok
  link.open()
}

// ❌ Wrong - async gap breaks user gesture
button.onclick = async () => {
  await someAsyncWork() // breaks it!
  link.open() // BLOCKED
}

// ❌ Wrong - setTimeout breaks user gesture
button.onclick = () => {
  setTimeout(() => link.open(), 100) // BLOCKED
}

Configuration

interface EdgeLinkConfig {
  // Required
  clientId: string              // Your OAuth client ID
  environment: EdgeEnvironment  // 'production' | 'sandbox'
  onSuccess: (result) => void   // Called on successful auth

  // Optional
  onExit?: (metadata) => void   // Called when user exits
  onEvent?: (event) => void     // Called for analytics events
  scopes?: EdgeScope[]          // Scopes to request (default: all)
  linkUrl?: string              // Custom Link URL/origin (dev only)
  redirectUri?: string          // Legacy popup callback URI (migration only)
}

The SDK derives the hosted Link URL from environment; sandbox defaults to https://sandbox-oauth.staging-app.edgeboost.io/oauth/link. linkUrl is only needed for nonstandard deployments. If provided as an origin, for example https://oauth.example.com, the SDK appends /oauth/link.

Popup integrations are origin-based. Register your frontend origin with EDGE for postMessage validation, for example:

  • https://app.partner.com
  • http://localhost:3000
  • http://localhost:5173

redirectUri is no longer required for popup completion. Keep it only while migrating an older integration that still sends a registered callback URL.

Callbacks

onSuccess

Called when user successfully authenticates and grants consent:

onSuccess: (result) => {
  // result.code - Authorization code (send to backend)
  // result.codeVerifier - PKCE verifier (send to backend)
  // result.state - State parameter (for validation)

  // IMPORTANT: Exchange tokens on your backend, not here!
  // The backend has your client secret, the browser doesn't.
}

onExit

Called when user exits the flow:

onExit: (metadata) => {
  switch (metadata.reason) {
    case 'user_closed':
      // User closed the popup
      break
    case 'popup_blocked':
      // Popup was blocked - show instructions
      alert('Please allow popups')
      break
    case 'error':
      // An error occurred
      console.error(metadata.error?.message)
      break
  }
}

onEvent

Called for analytics and debugging:

onEvent: (event) => {
  // event.eventName - 'OPEN' | 'CLOSE' | 'HANDOFF' | 'SUCCESS' | 'ERROR'
  // event.timestamp - Unix timestamp
  // event.metadata - Additional context

  analytics.track('edge_link_event', event)
}

Methods

MethodDescription
open(options?)Opens the Link popup (must be from click handler)
close()Closes the popup programmatically
destroy()Cleans up resources (call when done)
isOpen()Returns true if popup is open

Scopes

Request only the permissions you need:

import { EdgeLink, EDGE_SCOPES } from '@edge-markets/connect-link'

const link = new EdgeLink({
  clientId: 'your-client-id',
  environment: 'sandbox',
  scopes: [
    EDGE_SCOPES.USER_READ,    // Read profile
    EDGE_SCOPES.BALANCE_READ, // Read balance
    // EDGE_SCOPES.TRANSFER_WRITE is reserved and currently unavailable
  ],
  onSuccess: handleSuccess,
})

React Hook

The recommended way to use EdgeLink in React:

import { useEdgeLink } from '@edge-markets/connect-link'

function ConnectButton() {
  const { open, ready, isOpen, error } = useEdgeLink({
    clientId: process.env.NEXT_PUBLIC_EDGE_CLIENT_ID!,
    environment: 'sandbox',
    onSuccess: async (result) => {
      await fetch('/api/edge/exchange', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(result),
      })
    },
    onExit: (metadata) => {
      if (metadata.reason === 'popup_blocked') {
        alert('Please allow popups')
      }
    },
  })

  if (error) {
    return <div>Error: {error.message}</div>
  }

  return (
    <button onClick={() => open()} disabled={!ready || isOpen}>
      {isOpen ? 'Connecting...' : 'Connect EdgeBoost'}
    </button>
  )
}

Hook Return Values

PropertyTypeDescription
open(options?) => voidOpens the Link popup
readybooleanTrue when EdgeLink is initialized
isOpenbooleanTrue when popup is open
errorError | nullInitialization or runtime error

Manual React Example

For more control, you can use EdgeLink directly:

import { useEffect, useRef, useCallback } from 'react'
import { EdgeLink } from '@edge-markets/connect-link'

function ConnectButton() {
  const linkRef = useRef<EdgeLink | null>(null)

  useEffect(() => {
    linkRef.current = new EdgeLink({
      clientId: process.env.NEXT_PUBLIC_EDGE_CLIENT_ID!,
      environment: 'sandbox',
      onSuccess: async (result) => {
        await fetch('/api/edge/exchange', {
          method: 'POST',
          body: JSON.stringify(result),
        })
      },
      onExit: (metadata) => {
        if (metadata.reason === 'popup_blocked') {
          alert('Please allow popups')
        }
      },
    })

    return () => linkRef.current?.destroy()
  }, [])

  const handleClick = useCallback(() => {
    linkRef.current?.open()
  }, [])

  return (
    <button onClick={handleClick}>
      Connect EdgeBoost
    </button>
  )
}

How It Works

  1. User clicks button → link.open() is called
  2. Popup opens immediately → Shows branded loading state
  3. PKCE generated → Secure OAuth without client secret
  4. Popup navigates to Link page → User logs in & grants consent
  5. Code returned via postMessage → Secure cross-origin communication
  6. onSuccess called → You send code to backend for token exchange
┌─────────────┐     ┌─────────────────┐     ┌──────────────┐
│   Your App  │     │  EdgeLink Popup │     │ Your Backend │
└──────┬──────┘     └────────┬────────┘     └──────┬───────┘
       │                     │                     │
       │ link.open()         │                     │
       ├────────────────────►│                     │
       │                     │                     │
       │           (user logs in, grants consent)  │
       │                     │                     │
       │   postMessage(code) │                     │
       │◄────────────────────┤                     │
       │                     │                     │
       │ onSuccess(result)   │                     │
       ├─────────────────────┼────────────────────►│
       │                     │   POST /api/exchange │
       │                     │                     │
       │                     │   tokens             │
       │◄────────────────────┼─────────────────────┤
       │                     │                     │

Security

  • PKCE - Prevents authorization code interception
  • State parameter - Prevents CSRF attacks
  • Origin validation - postMessage only accepted from expected origin
  • No client secret in browser - Token exchange happens on your backend
  • @edge-markets/connect - Core types and utilities
  • @edge-markets/connect-node - Server SDK for token exchange

License

MIT

版本与发布记录

@edge-markets/connect-link 共发布 17 个版本,首次发布于 2026/01/21;过去 12 个月发布了 17 个版本。

版本发布日期距今
3.0.0latest2026/10/2717 天前
2.0.02026/07/293 个月前
1.9.12026/07/273 个月前
1.9.02026/07/273 个月前
1.8.12026/07/024 个月前
1.8.02026/07/024 个月前

关于 @edge-markets/connect-link 的常见问题

@edge-markets/connect-link 是什么?

Browser SDK for EDGE Connect popup authentication

如何安装 @edge-markets/connect-link?

在项目目录运行 npm install @edge-markets/connect-link,或使用 pnpm add / yarn add / bun add。

@edge-markets/connect-link 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@edge-markets/connect-link 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@edge-markets/connect-link 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.23.4。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@edge-markets/connect-link 可以商用吗?

@edge-markets/connect-link 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@edge-markets/connect-link 的下载量有多少?

根据 npm 官方下载统计,@edge-markets/connect-link 在 2026/10/13 – 2026/11/11 这 30 天内被下载 16,422 次,日均约 547 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@edge-markets/connect-link 还在维护吗?

最新版本 3.0.0 发布于 2026/10/27(17 天前);至今共发布 17 个版本,其中过去 12 个月发布了 17 个;首次发布于 2026/01/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。