swingauth
TypeScript icon, indicating that this package has built-in type declarations

1.1.1 • Public • Published

SwingAuth SDK

A comprehensive authentication solution for React applications with cross-domain support, created by BigSur Corp.

Features

  • 🔐 Multiple authentication methods (Email, Username, Phone, Google, GitHub)
  • 🌐 Cross-domain authentication support
  • 🎨 Beautiful, customizable UI components
  • 🚀 Easy integration with React applications
  • 🔒 Secure token-based authentication
  • 📱 Mobile-responsive design
  • ⚡ TypeScript support
  • 🎯 Zero configuration required
  • 🛡️ COOP-compliant OAuth implementation

Installation

npm install swingauth

or

yarn add swingauth

Quick Start

1. Wrap your app with SwingAuthProvider

import React from 'react';
import { SwingAuthProvider } from 'swingauth';

function App() {
  const config = {
    apiKey: 'your-api-key',
    apiBaseUrl: 'https://your-swingauth-service.com', // Optional: for cross-domain
    allowedMethods: ['email', 'google', 'github'],
    onSuccess: (data) => {
      console.log('Authentication successful:', data);
    },
    onError: (error) => {
      console.error('Authentication error:', error);
    }
  };

  return (
    <SwingAuthProvider config={config}>
      <YourApp />
    </SwingAuthProvider>
  );
}

export default App;

2. Use the authentication hook

import React from 'react';
import { useSwingAuth, SwingAuthButton } from 'swingauth';

function YourComponent() {
  const { isAuthenticated, user, logout } = useSwingAuth();

  if (isAuthenticated) {
    return (
      <div>
        <h1>Welcome, {user.name}!</h1>
        <button onClick={logout}>Logout</button>
      </div>
    );
  }

  return (
    <div>
      <h1>Please sign in</h1>
      <SwingAuthButton mode="login">Login</SwingAuthButton>
      <SwingAuthButton mode="signup">Sign Up</SwingAuthButton>
    </div>
  );
}

Configuration

SwingAuthConfig

Property Type Required Description
apiKey string Yes Your SwingAuth API key
apiBaseUrl string No Base URL for SwingAuth service (for cross-domain)
redirectUrl string No URL to redirect after successful authentication
allowedMethods AuthMethod[] No Array of allowed authentication methods
onSuccess function No Callback function called on successful authentication
onError function No Callback function called on authentication error

Cross-Domain Setup

For cross-domain authentication, specify the apiBaseUrl pointing to your SwingAuth service:

const config = {
  apiKey: 'your-api-key',
  apiBaseUrl: 'https://swingauth.bigsur.in', // Your SwingAuth service URL
  allowedMethods: ['email', 'username', 'google', 'github']
};

Local Development:

const config = {
  apiKey: 'your-api-key',
  // apiBaseUrl not needed for same-domain
  allowedMethods: ['email', 'username', 'google', 'github']
};

Authentication Methods

  • email - Email and password authentication
  • username - Username and password authentication
  • phone - Phone number and password authentication
  • google - Google OAuth authentication
  • github - GitHub OAuth authentication

Components

SwingAuthButton

A customizable button component that triggers the authentication modal.

import { SwingAuthButton } from 'swingauth';

<SwingAuthButton 
  mode="login" 
  className="custom-class"
>
  Sign In
</SwingAuthButton>

Props

Property Type Default Description
mode 'login' | 'signup' 'login' Authentication mode
children ReactNode - Button content
className string - Additional CSS classes

Hooks

useSwingAuth

Returns the current authentication state and methods.

const {
  isAuthenticated, // boolean - whether user is authenticated
  user,           // object - current user data
  token,          // string - authentication token
  showAuth,       // function - show authentication modal
  logout          // function - logout current user
} = useSwingAuth();

Framework Integration Examples

Next.js App Router

// app/providers.tsx
"use client"

import { SwingAuthProvider } from 'swingauth'

export function Providers({ children }) {
  return (
    <SwingAuthProvider
      config={{
        apiKey: process.env.NEXT_PUBLIC_SWINGAUTH_API_KEY,
        apiBaseUrl: "https://swingauth.bigsur.in",
        allowedMethods: ['email', 'username', 'google', 'github']
      }}
    >
      {children}
    </SwingAuthProvider>
  )
}

// app/layout.tsx
import { Providers } from './providers'

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  )
}

React with Vite

// src/main.jsx
import { SwingAuthProvider } from 'swingauth'

function App() {
  return (
    <SwingAuthProvider
      config={{
        apiKey: import.meta.env.VITE_SWINGAUTH_API_KEY,
        apiBaseUrl: "https://swingauth.bigsur.in",
        allowedMethods: ['email', 'username', 'google', 'github']
      }}
    >
      <YourApp />
    </SwingAuthProvider>
  )
}

API Integration

The SDK automatically handles API communication with your SwingAuth backend. Make sure your backend is configured with the correct API endpoints:

  • POST /api/auth/login - User login
  • POST /api/auth/signup - User registration
  • POST /api/auth/oauth - OAuth authentication
  • GET /api/auth/github - GitHub OAuth initiation
  • GET /api/auth/google - Google OAuth initiation

Cross-Domain Features

v1.1.0 New Features

  • Cross-Origin-Opener-Policy (COOP) Compliance: Fixed OAuth popup issues across domains
  • Configurable API Base URL: Point to any SwingAuth service instance
  • Timeout-based Error Handling: 60-second timeout for OAuth flows
  • Extension Message Filtering: Automatically filters out MetaMask and other extension messages
  • SSR Compatibility: Works with server-side rendering frameworks

Migration from v1.0.0

Before (v1.0.0):

const config = {
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret', // ❌ Removed
  allowedMethods: ['email', 'google']
};

After (v1.1.0):

const config = {
  apiKey: 'your-api-key',
  apiBaseUrl: 'https://swingauth.bigsur.in', // ✅ New: for cross-domain
  allowedMethods: ['email', 'google']
};

Styling

The SDK comes with beautiful default styles, but you can customize the appearance using CSS classes or by overriding the default styles.

Custom CSS

.swingauth-modal {
  /* Custom modal styles */
}

.swingauth-button {
  /* Custom button styles */
}

TypeScript Support

The SDK is built with TypeScript and provides full type definitions.

import { SwingAuthConfig, AuthMethod, useSwingAuth } from 'swingauth';

const config: SwingAuthConfig = {
  apiKey: 'your-api-key',
  apiBaseUrl: 'https://swingauth.bigsur.in',
  allowedMethods: ['email', 'google'] as AuthMethod[]
};

Examples

Basic Login/Signup

import React from 'react';
import { SwingAuthProvider, useSwingAuth, SwingAuthButton } from 'swingauth';

function AuthExample() {
  const { isAuthenticated, user, logout } = useSwingAuth();

  return (
    <div>
      {isAuthenticated ? (
        <div>
          <h2>Welcome back, {user.name}!</h2>
          <button onClick={logout}>Logout</button>
        </div>
      ) : (
        <div>
          <SwingAuthButton mode="login">Login</SwingAuthButton>
          <SwingAuthButton mode="signup">Create Account</SwingAuthButton>
        </div>
      )}
    </div>
  );
}

function App() {
  return (
    <SwingAuthProvider config={{
      apiKey: 'your-api-key',
      apiBaseUrl: 'https://swingauth.bigsur.in'
    }}>
      <AuthExample />
    </SwingAuthProvider>
  );
}

Cross-Domain OAuth Integration

const config = {
  apiKey: 'your-api-key',
  apiBaseUrl: 'https://swingauth.bigsur.in', // Your SwingAuth service
  allowedMethods: ['google', 'github'],
  onSuccess: (data) => {
    // Handle successful OAuth login
    console.log('OAuth success:', data);
    // User data is automatically stored in localStorage
  },
  onError: (error) => {
    console.error('OAuth error:', error);
  }
};

Protected Routes

import { useSwingAuth } from 'swingauth'

function ProtectedPage() {
  const { isAuthenticated, user, showAuth } = useSwingAuth()
  
  if (!isAuthenticated) {
    return (
      <div>
        <h1>Access Denied</h1>
        <p>Please sign in to access this page.</p>
        <button onClick={() => showAuth('login')}>Sign In</button>
      </div>
    )
  }
  
  return (
    <div>
      <h1>Protected Content</h1>
      <p>Welcome, {user.name}! This is protected content.</p>
    </div>
  )
}

Troubleshooting

OAuth Issues

If you're experiencing OAuth authentication issues:

  1. Check CORS settings on your SwingAuth service
  2. Verify OAuth app configuration (GitHub/Google) redirect URLs
  3. Ensure popup blockers are disabled during testing
  4. Check console logs for detailed error messages

Cross-Domain Setup

For production cross-domain setup:

  1. Configure your OAuth apps to redirect to your SwingAuth service domain
  2. Set up proper CORS headers on your SwingAuth service
  3. Use HTTPS for both your app and SwingAuth service

Changelog

v1.1.0

  • ✅ Added cross-domain authentication support
  • ✅ Added apiBaseUrl configuration option
  • ✅ Removed deprecated apiSecret parameter
  • ✅ Fixed Cross-Origin-Opener-Policy (COOP) issues
  • ✅ Added timeout-based error handling for OAuth
  • ✅ Improved extension message filtering
  • ✅ Enhanced SSR compatibility

v1.0.0

  • 🎉 Initial release
  • ✅ Basic authentication methods
  • ✅ OAuth support (GitHub, Google)
  • ✅ React hooks and components

License

MIT License - see LICENSE file for details.

Support

For support and questions, please visit https://bigsur.in or create an issue on our GitHub repository.

Created by BigSur Corp

SwingAuth is proudly created and maintained by BigSur Corp. Visit us at bigsur.in.

Package Sidebar

Install

npm i swingauth

Homepage

bigsur.in

Weekly Downloads

8

Version

1.1.1

License

MIT

Unpacked Size

235 kB

Total Files

10

Last publish

Collaborators

  • bigsur