cygnt-react-sdk
v1.0.9
Published
React SDK for integrating Cygnt link validation and management into React applications
Downloads
311
Maintainers
Readme
@cygnt/react-sdk
A React SDK for integrating Cygnt link validation and management into your React applications.
Features
- 🔐 Automatic API Detection: Automatically switches between sandbox and production APIs based on your API key
- 🎯 TypeScript Support: Full TypeScript support with comprehensive type definitions
- ⚡ React Hooks: Easy-to-use React hooks for seamless integration
- 🛡️ Error Handling: Built-in error handling and validation with clear state separation
- 🔄 Auto-validation: Automatic validation when required props are provided
- 📦 Dual Package Format: Supports both CommonJS and ES6 modules for maximum compatibility
- 🎨 Modern API Design: Clean
{ data, loading, error }return structure following React best practices - 🔍 Comprehensive Testing: 100% test coverage with 71+ tests ensuring reliability
Installation
npm install @cygnt/react-sdk
# or
yarn add @cygnt/react-sdk
# or
pnpm add @cygnt/react-sdkPackage Compatibility
This package supports both CommonJS and ES6 module systems:
- CommonJS:
require('@cygnt/react-sdk')- for Node.js and older bundlers - ES6 Modules:
import { ... } from '@cygnt/react-sdk'- for modern bundlers and browsers
The package automatically detects your environment and provides the appropriate format, resolving the "Unexpected token 'export'" error that some users experienced.
Peer Dependencies
This package requires React 17.0.0 or higher:
{
"peerDependencies": {
"react": ">=17.0.0",
"react-dom": ">=17.0.0"
}
}Quick Start
Basic Usage
import { useCygntValidation } from '@cygnt/react-sdk';
function MyComponent() {
const { data, loading, error } = useCygntValidation({
apiKey: 'your-api-key',
env: 'sandbox',
extUserId: 'user123',
configurationId: 'config456'
});
if (loading) {
return <div>Validating...</div>;
}
if (error) {
return <div>Validation failed: {error}</div>;
}
if (data?.status === 'success') {
return <div>Welcome, {data.email}!</div>;
}
return <div>Validation status: {data?.status}</div>;
}With CygntLink Component
import { CygntLink } from '@cygnt/react-sdk';
function App() {
return (
<CygntLink
apiKey="your-api-key"
extUserId="user123"
configurationId="config456"
redirectUrl="https://your-app.com/dashboard"
/>
);
}
// With custom styling and content
function CustomExample() {
return (
<CygntLink
apiKey="your-api-key"
extUserId="user123"
configurationId="config456"
redirectUrl="https://your-app.com/dashboard"
email="[email protected]"
className="btn btn-primary"
style={{ fontSize: '16px' }}
>
Click here to start validation
</CygntLink>
);
}API Reference
useCygntValidation Hook
A React hook that automatically validates Cygnt links and retrieves user information.
Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| apiKey | string | ✅ | API key for authentication |
| env | 'sandbox' \| 'production' | ✅ | Selects API base URL for validation requests |
| extUserId | string | ✅ | External user identifier |
| configurationId | string | ✅ | Configuration identifier for the link |
Returns
Returns an object with the following properties:
| Property | Type | Description |
|----------|------|-------------|
| data | ValidationResponse \| null | Validation data containing user information and status, or null if not yet loaded |
| loading | boolean | Boolean indicating if validation is currently in progress |
| error | string \| null | Error message string if validation failed, or null if no error |
ValidationResponse Object
When data is not null, it contains the following properties:
| Property | Type | Description |
|----------|------|-------------|
| email | string | User's email address |
| userId | string | Internal user ID |
| extUserId | string | External user ID provided by the client |
| enterpriseId | string | Enterprise identifier |
| configurationId | string | Configuration identifier |
| linkId | string | Link identifier |
| status | ValidationStatus | Current validation status |
Validation Status Types
'pending'- Validation is pending'success'- Validation completed successfully'inactive'- Link is inactive'started'- Validation has started'expired'- Link has expired'error'- Validation encountered an error
CygntLink Component
A React component that renders a clickable link for starting the Cygnt validation process. This component automatically generates the proper enrollment URL and opens it in a new tab when clicked.
Props
| Prop | Type | Required | Description |
|------|------|----------|-------------|
| apiKey | string | ✅ | API key for authentication |
| extUserId | string | ✅ | External user identifier |
| configurationId | string | ✅ | Configuration identifier |
| redirectUrl | string | ✅ | URL to redirect to after successful validation |
| email | string | ❌ | Optional email address for pre-filling |
| children | ReactNode | ❌ | Custom content (defaults to "Start Cygnt Validation") |
Additional Features
- Automatic URL Generation: Uses the
useCygntLinkhook internally - Security: Opens in new tab with
rel="noopener noreferrer" - Flexibility: Accepts all standard HTML anchor attributes
- Customization: Supports custom children and styling
useCygntLink Hook
A utility hook for generating Cygnt enrollment URLs programmatically. Useful when you need the URL but don't want to render a link component.
Returns
Returns a complete enrollment URL string with all parameters properly encoded.
Example
import { useCygntLink } from '@cygnt/react-sdk';
function MyComponent() {
const enrollmentUrl = useCygntLink({
apiKey: 'your-api-key',
extUserId: 'user123',
configurationId: 'config456',
redirectUrl: 'https://your-app.com/dashboard',
email: '[email protected]'
});
const handleClick = () => {
window.open(enrollmentUrl, '_blank');
};
return (
<button onClick={handleClick}>
Start Enrollment
</button>
);
}Configuration
The SDK automatically detects the appropriate API endpoint based on your API key:
- Sandbox API:
https://sandbox-api.cygnt.com/bk/v1 - Production API:
https://api.cygnt.com/bk/v1
If your API key contains the word "sandbox", it will automatically use the sandbox environment.
Error Handling
The SDK includes comprehensive error handling with clear separation of concerns:
- Loading State: The
loadingboolean indicates when validation is in progress - Error State: The
errorstring contains descriptive error messages when validation fails - Data State: The
dataobject contains validation results when successful, ornullwhen not yet loaded - Network Errors: Automatically caught and provided as error messages
- Invalid Responses: Handled gracefully with appropriate error messages
- Console Logging: Errors are logged to the console for debugging purposes
Error Handling Best Practices
import { useCygntValidation } from '@cygnt/react-sdk';
function ErrorHandlingExample() {
const { data, loading, error } = useCygntValidation({
apiKey: 'your-api-key',
env: 'sandbox',
extUserId: 'user123',
configurationId: 'config456'
});
// Handle loading state
if (loading) {
return <div>Loading...</div>;
}
// Handle error state
if (error) {
return (
<div className="error">
<h3>Something went wrong</h3>
<p>{error}</p>
<button onClick={() => window.location.reload()}>
Try Again
</button>
</div>
);
}
// Handle successful validation
if (data?.status === 'success') {
return <div>Welcome, {data.email}!</div>;
}
// Handle other validation statuses
return <div>Status: {data?.status}</div>;
}Examples
Advanced Usage with Custom UI
import { useCygntValidation } from '@cygnt/react-sdk';
function ValidationStatus() {
const { data, loading, error } = useCygntValidation({
apiKey: process.env.REACT_APP_CYGNT_API_KEY,
env: 'sandbox',
extUserId: 'user123',
configurationId: 'config456'
});
const renderStatus = () => {
if (loading) {
return (
<div className="loading">
<p>Validating...</p>
</div>
);
}
if (error) {
return (
<div className="error">
<h3>Validation Failed</h3>
<p>Error: {error}</p>
<p>Please try again or contact support.</p>
</div>
);
}
if (!data) {
return (
<div className="loading">
<p>Initializing...</p>
</div>
);
}
switch (data.status) {
case 'success':
return (
<div className="success">
<h3>Welcome back!</h3>
<p>Email: {data.email}</p>
<p>User ID: {data.userId}</p>
</div>
);
case 'expired':
return (
<div className="warning">
<h3>Link Expired</h3>
<p>This validation link has expired.</p>
</div>
);
case 'pending':
return (
<div className="info">
<h3>Validation Pending</h3>
<p>Your validation is being processed.</p>
</div>
);
default:
return (
<div className="info">
<h3>Status: {data.status}</h3>
<p>Current validation status: {data.status}</p>
</div>
);
}
};
return (
<div className="validation-container">
{renderStatus()}
</div>
);
}Integration with Form Components
import { useCygntValidation } from '@cygnt/react-sdk';
function UserProfile() {
const [email, setEmail] = useState('');
const { data, loading, error } = useCygntValidation({
apiKey: 'your-api-key',
env: 'sandbox',
extUserId: 'user123',
configurationId: 'config456'
});
useEffect(() => {
if (data?.email) {
setEmail(data.email);
}
}, [data?.email]);
return (
<form>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter your email"
disabled={loading}
/>
{loading && <p className="loading">Loading profile...</p>}
{error && (
<p className="error">Failed to load profile: {error}</p>
)}
{data?.status === 'success' && (
<p className="success">Profile loaded successfully!</p>
)}
</form>
);
}Migration Guide
Upgrading from Previous Versions
If you're upgrading from a previous version that returned a ValidationResponse object directly, here's how to migrate to the new { data, loading, error } structure:
Before (Old API)
const validation = useCygntValidation({
apiKey: 'your-api-key',
env: 'sandbox',
extUserId: 'user123',
configurationId: 'config456'
});
if (validation.status === 'success') {
return <div>Welcome, {validation.email}!</div>;
}
if (validation.status === 'error') {
return <div>Validation failed</div>;
}
return <div>Validating...</div>;After (New API)
const { data, loading, error } = useCygntValidation({
apiKey: 'your-api-key',
env: 'sandbox',
extUserId: 'user123',
configurationId: 'config456'
});
if (loading) {
return <div>Validating...</div>;
}
if (error) {
return <div>Validation failed: {error}</div>;
}
if (data?.status === 'success') {
return <div>Welcome, {data.email}!</div>;
}
return <div>Status: {data?.status}</div>;Key Changes
- Return Structure: Now returns
{ data, loading, error }instead of a direct object - Loading State: Use
loadingboolean instead of checking status - Error Handling: Use
errorstring for error messages instead of status - Data Access: Access validation data through
dataproperty with optional chaining - Better UX: Clear separation allows for better loading states and error handling
Troubleshooting
"Unexpected token 'export'" Error
If you encounter this error, it typically means your bundler is trying to parse ES6 modules in a CommonJS environment. This package now supports both formats automatically, but if you continue to have issues:
Clear your node_modules and reinstall:
rm -rf node_modules package-lock.json npm installCheck your bundler configuration - ensure it's configured to handle ES6 modules properly
Update to the latest version - this issue was fixed in version 1.0.2
Import Issues
If you're having trouble importing the package, try these approaches:
// ES6 Modules (recommended)
import { useCygntValidation, CygntLink } from '@cygnt/react-sdk';
// CommonJS (if needed)
const { useCygntValidation, CygntLink } = require('@cygnt/react-sdk');Development
Building the Package
npm run buildThis generates both CommonJS and ES6 module formats:
dist/index.cjs- CommonJS format for Node.js compatibilitydist/index.esm.js- ES6 modules for modern bundlersdist/index.d.ts- TypeScript declarations
TypeScript
This package is written in TypeScript and includes type definitions. The build process generates both JavaScript and TypeScript declaration files.
License
MIT © Levon Azizyan
