Skip to content

Authentication & Profile

Sesamy JS provides comprehensive authentication and profile management with support for multiple login flows and user data management.

Authentication

The SDK provides comprehensive authentication methods with support for both redirect and popup-based flows.

login()

Smart login that automatically chooses the best authentication method based on browser context.

Parameters:

  • options (optional):
    • appState: Any JSON-serializable data to preserve during authentication (e.g., { source: 'registration-wall', articleId: '123' })
    • authorizationParams:
      • audience: API audience
      • scope: OAuth scopes
      • login_hint: Pre-fill email
      • organization: Auth0 organization
      • redirect_uri: Post-login redirect URL

Returns: Promise<void>

Example:

javascript
await window.sesamy.auth.login({
  authorizationParams: {
    login_hint: 'user@example.com',
  },
});

Example with metadata tracking:

javascript
// Track login source for analytics
await window.sesamy.auth.login({
  appState: {
    source: 'registration-wall',
    articleId: 'article-123',
    campaign: 'spring-2025',
  },
});

loginWithRedirect()

Redirects user to Auth0 hosted login page. Best for desktop browsers.

Parameters:

  • Same as login()

Returns: Promise<void>

Example:

javascript
await window.sesamy.auth.loginWithRedirect({
  authorizationParams: {
    redirect_uri: window.location.origin + '/callback',
  },
});

loginWithPopup()

Opens login in a popup window. Better for maintaining page state and works better in incognito mode.

Note: To prevent automatic page refresh after authentication, listen for sesamyJsAuthenticated event and call preventDefault().

Parameters:

  • Same as login()

Returns: Promise<void>

Example:

javascript
// Prevent auto-refresh after login
window.addEventListener('sesamyJsAuthenticated', (event) => {
  event.preventDefault();
  console.log('User authenticated!');
});

await window.sesamy.auth.loginWithPopup({
  authorizationParams: {
    login_hint: 'user@example.com',
  },
});

logout()

Logs out the user and optionally redirects.

Parameters:

  • options (optional):
    • returnTo: URL to redirect after logout

Returns: Promise<void>

Example:

javascript
await window.sesamy.auth.logout({
  returnTo: 'https://yoursite.com',
});

isAuthenticated()

Checks if user is currently authenticated.

Returns: Promise<boolean>

Example:

javascript
const isAuth = await window.sesamy.auth.isAuthenticated();
if (isAuth) {
  console.log('User is logged in');
}

getTokenSilently()

Retrieves access token without user interaction.

Parameters:

  • throwOnUnauthorized (boolean, default: true): Throw error if not authenticated
  • forceRefresh (boolean, default: false): Force token refresh

Returns: Promise<string | null>

Example:

javascript
const token = await window.sesamy.auth.getTokenSilently();
// Use token for API calls

setToken()

Manually set an access token.

Parameters:

  • accessToken (string): The access token
  • expiresIn (number, optional): Token expiration in seconds

Returns: Promise<void>

Example:

javascript
await window.sesamy.auth.setToken('your.jwt.token', 3600);

Profile Management

profile.get()

Fetches the user's profile information.

Returns: Promise<Profile | null>

Profile Type:

text
type Profile = {
  userId: string;
  firstName?: string;
  lastName?: string;
  emailVerified: boolean;
  email: string;
  name?: string;
  locale?: string;
  picture?: string;
  createdAt: string;
  updatedAt: string;
  mobilePhone?: string;
  tags: string[];
  user_metadata?: Record<string, string | number>;
  billingAddress?: Address;
  deliveryAddress?: Address;
};

Example:

javascript
const profile = await window.sesamy.profile.get();
if (profile) {
  console.log('User email:', profile.email);
  console.log('Name:', profile.firstName, profile.lastName);
  console.log('Email verified:', profile.emailVerified);
}

profile.update()

Updates the user's profile information.

Parameters:

  • profile (Partial<Profile>): Fields to update

Returns: Promise<boolean>

Example:

javascript
const success = await window.sesamy.profile.update({
  firstName: 'John',
  lastName: 'Doe',
  mobilePhone: '+1234567890',
  billingAddress: {
    street: '123 Main St',
    city: 'New York',
    state: 'NY',
    postalCode: '10001',
    country: 'US',
  },
});

if (success) {
  console.log('Profile updated successfully');
}

profile.openHostedAccountPage()

Opens the Sesamy hosted account management page where users can manage their subscriptions, payment methods, and personal information.

Example:

javascript
// Add to a "My Account" button
document.querySelector('#account-btn').addEventListener('click', () => {
  window.sesamy.profile.openHostedAccountPage();
});

profile.isSpotifyLinked()

Checks if the user has linked their Spotify account.

Returns: Promise<boolean>

Example:

javascript
const isLinked = await window.sesamy.profile.isSpotifyLinked();
if (isLinked) {
  console.log('Spotify account is linked');
}

profile.unlinkSpotify()

Unlinks the user's Spotify account.

Returns: Promise<void>

Example:

javascript
await window.sesamy.profile.unlinkSpotify();
console.log('Spotify account unlinked');

Cross-Domain Authentication

For applications spanning multiple domains (e.g., white-label sites, multi-region deployments), Sesamy JS supports automatic domain selection:

javascript
{
  auth: {
    clientId: "your-client-id",
    domains: [
      "auth.brand1.com",
      "auth.brand2.com",
      "auth.example.co.uk"
    ],
    domain: "default-auth.example.com"  // Fallback domain
  }
}

The SDK automatically selects the appropriate auth domain based on the current page's top-level domain, ensuring seamless authentication across your domain portfolio.

Common Patterns

Protected Content

javascript
window.addEventListener('sesamyJsReady', async () => {
  const isAuth = await window.sesamy.auth.isAuthenticated();

  if (isAuth) {
    const profile = await window.sesamy.profile.get();
    document.querySelector('.user-name').textContent = profile.name;
    document.querySelector('.premium-content').style.display = 'block';
  } else {
    document.querySelector('.login-prompt').style.display = 'block';
  }
});

Login/Logout Button

javascript
const authBtn = document.querySelector('#auth-btn');

window.addEventListener('sesamyJsReady', async () => {
  const updateAuthButton = async () => {
    const isAuth = await window.sesamy.auth.isAuthenticated();

    if (isAuth) {
      const profile = await window.sesamy.profile.get();
      authBtn.textContent = `Logout (${profile.email})`;
      authBtn.onclick = () => window.sesamy.auth.logout();
    } else {
      authBtn.textContent = 'Login';
      authBtn.onclick = () => window.sesamy.auth.login();
    }
  };

  await updateAuthButton();

  // Update button after authentication changes
  window.addEventListener('sesamyJsAuthenticated', updateAuthButton);
  window.addEventListener('sesamyJsLoggedOut', updateAuthButton);
});

Profile Form

javascript
window.addEventListener('sesamyJsReady', async () => {
  const profile = await window.sesamy.profile.get();

  if (profile) {
    // Pre-fill form
    document.querySelector('#firstName').value = profile.firstName || '';
    document.querySelector('#lastName').value = profile.lastName || '';
    document.querySelector('#email').value = profile.email;
  }

  // Handle form submission
  document.querySelector('#profileForm').addEventListener('submit', async (e) => {
    e.preventDefault();

    const success = await window.sesamy.profile.update({
      firstName: document.querySelector('#firstName').value,
      lastName: document.querySelector('#lastName').value,
      mobilePhone: document.querySelector('#phone').value,
    });

    if (success) {
      alert('Profile updated successfully!');
    }
  });
});

Login Paywall with Tracking

Track where users are logging in from using appState:

javascript
// Custom login paywall component
class LoginPaywall extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `
      <div class="paywall">
        <h2>Subscribe to continue reading</h2>
        <button id="paywall-login">Sign up or Login</button>
      </div>
    `;

    this.querySelector('#paywall-login').addEventListener('click', () => {
      window.sesamy.auth.login({
        appState: {
          source: 'registration-wall',
          articleId: this.getAttribute('article-id'),
          contentType: this.getAttribute('content-type') || 'article',
        },
      });
    });
  }
}

customElements.define('login-paywall', LoginPaywall);

// Listen for authentication with metadata
window.addEventListener('sesamyJsAuthenticated', (event) => {
  const { appState, email, sub } = event.detail;

  if (appState?.source === 'registration-wall') {
    // Track conversion
    console.log('User registered from paywall', {
      source: appState.source,
      articleId: appState.articleId,
      contentType: appState.contentType,
      userId: sub,
    });

    // Send to analytics
    if (window.gtag) {
      window.gtag('event', 'registration_completed', {
        source: appState.source,
        article_id: appState.articleId,
      });
    }
  }
});

Usage in HTML:

html
<login-paywall article-id="spring-news-2025" content-type="premium-article"></login-paywall>

Next Steps

Released under the MIT License.