Skip to content

URL Query String Handlers

Sesamy JS automatically handles special query parameters and URL fragments to provide seamless integration with authentication flows, content access, and debugging. These handlers process URL parameters automatically on page load and clean them up after processing.

Authentication Handlers

#access_token

Handles access tokens passed in the URL hash fragment (typically after OAuth redirects).

Usage:

https://yoursite.com/article#access_token=eyJhbGc...

Behavior:

  • Extracts the access token from the URL hash
  • Stores it in the session using setToken()
  • Removes the token from the URL for security
  • Updates browser history without the token

Example Flow:

javascript
// User is redirected back from authentication
// URL: https://yoursite.com/page#access_token=eyJhbGc...
// Sesamy JS automatically:
// 1. Captures the token
// 2. Stores it securely
// 3. Cleans URL to: https://yoursite.com/page

?sesamy-login / ?sesamy_login

Forces authentication if the user is not already logged in.

Usage:

https://yoursite.com/premium-article?sesamy-login=true

Behavior:

  • Checks if user is authenticated
  • If not authenticated, triggers loginWithRedirect()
  • Removes the parameter from URL after processing
  • Does nothing if user is already authenticated

Use Cases:

  • Deep linking to premium content that requires login
  • Email campaigns directing to subscriber-only content
  • Social media links to gated articles

Example:

html
<!-- Share link that requires login -->
<a href="https://yoursite.com/article?sesamy-login=true"> Read Premium Article </a>

?sesamy-user

Ensures a specific user is logged in, switching accounts if necessary.

Usage:

https://yoursite.com/article?sesamy-user=user@example.com

Behavior:

  • Checks the current logged-in user's email
  • If email doesn't match, clears cache and initiates login with the specified email as hint
  • If email matches, continues normally
  • Removes the parameter from URL after processing

Use Cases:

  • Account-specific links in email campaigns
  • Support/admin tools for testing specific user accounts
  • Family sharing scenarios where specific account must be used

Security Note: This parameter only provides a login hint. Users still need valid credentials.

Example:

javascript
// Email campaign link for specific subscriber
// URL: https://yoursite.com/article?sesamy-user=subscriber@example.com
// If current user is different, they'll be prompted to switch accounts

Content Access Handlers

?sesamy-token / ?token

Handles signed link tokens for temporary or shared content access.

Usage:

https://yoursite.com/article?sesamy-token=eyJhbGc...

Behavior:

  • Extracts and validates the JWT token
  • Parses token payload containing access information
  • Creates a temporary entitlement from the token
  • Stores the signed link in session
  • Removes the parameter from URL

Token Payload Example:

json
{
  "url": "https://yoursite.com/article",
  "n": "Reader Name",
  "e": "reader@example.com",
  "s": "article-sku",
  "p": "purchase-option-id",
  "pid": "publisher-content-id",
  "iat": 1726583215,
  "exp": 1726597615
}

Use Cases:

  • Gift access links
  • Time-limited promotional access
  • Shared content links with expiration
  • Newsletter subscriber access

Example:

javascript
// Generate signed link (backend)
const signedUrl = generateSignedLink({
  url: 'https://yoursite.com/article',
  email: 'reader@example.com',
  expiresIn: 86400, // 24 hours
});

// Share link
// https://yoursite.com/article?sesamy-token=eyJhbGc...

?sesamy-purchase

Indicates a successful purchase and triggers post-purchase events.

Usage:

https://yoursite.com/success?sesamy-purchase=article-sku

Behavior:

  • Triggers PURCHASE event with the item SKU
  • Clears SDK cache to refresh entitlements
  • Removes the parameter from URL
  • Logs the purchase for debugging

Use Cases:

  • Post-checkout redirects
  • Purchase confirmation pages
  • Analytics tracking after purchase

Example:

javascript
// In checkout flow
const checkout = await window.sesamy.checkouts.create({
  items: [{ sku: 'premium_article' }],
  redirectUrl: 'https://yoursite.com/article?sesamy-purchase=premium_article',
});

// After redirect, listen for purchase event
window.addEventListener('sesamy:purchase', (event) => {
  console.log('Purchase completed:', event.detail.itemSrc);
  // Show success message, unlock content, etc.
});

Cache & State Handlers

?sesamy-refresh / ?force-refetch-entitlements

Forces a refresh of cached entitlements and user data.

Usage:

https://yoursite.com/article?sesamy-refresh=true

Behavior:

  • Clears the Sesamy SDK cache
  • Forces fresh data fetch on next API call
  • Removes the parameter from URL
  • Updates browser history

Use Cases:

  • Debugging access issues
  • After subscription changes
  • Testing entitlement updates
  • Support tools for cache-related issues

Example:

html
<!-- Add refresh link for debugging -->
<a href="?sesamy-refresh=true">Refresh Access</a>

<!-- Or programmatically -->
<script>
  function refreshAccess() {
    window.location.href = window.location.pathname + '?sesamy-refresh=true';
  }
</script>

Note: force-refetch-entitlements is deprecated but still supported for backward compatibility.

Debug Handlers

?sesamy-debug

Enables or disables debug logging in the browser console.

Usage:

https://yoursite.com/article?sesamy-debug=true

Parameters:

  • true - Enable debug logging
  • false - Disable debug logging

Behavior:

  • Enables detailed console logging when set to true
  • Persists debug state in localStorage
  • Removes the parameter from URL
  • Shows detailed API calls, entitlement checks, and internal operations

Use Cases:

  • Troubleshooting integration issues
  • Debugging authentication flows
  • Investigating access control problems
  • Development and testing

Console Output Examples:

javascript
// With ?sesamy-debug=true
[Sesamy] Checking access for: https://yoursite.com/article
[Sesamy] User authenticated: true
[Sesamy] Entitlements found: 3
[Sesamy] Access granted via: subscription-monthly

Example:

html
<!-- Enable debug mode -->
<a href="?sesamy-debug=true">Enable Debug Mode</a>

<!-- Disable debug mode -->
<a href="?sesamy-debug=false">Disable Debug Mode</a>

<!-- Check debug status -->
<script>
  // Debug state persists across page loads
  console.log('Debug enabled:', localStorage.getItem('sesamy-debug') === 'true');
</script>

Best Practices

URL Cleanup

All handlers automatically clean up query parameters after processing to:

  • Prevent accidental token exposure in shared URLs
  • Keep URLs clean and user-friendly
  • Avoid processing the same parameter multiple times
  • Maintain browser history integrity

Security Considerations

Access Tokens:

  • Always passed in hash fragment (#access_token), not query string
  • Automatically removed from URL history
  • Never logged or exposed in analytics

Signed Tokens:

  • Time-limited with expiration dates
  • Validated using JWT signatures
  • Cannot be modified without invalidation

User Switching:

  • sesamy-user only provides login hint
  • Actual authentication still required
  • Credentials are never passed in URL

Combining Parameters

Multiple Sesamy parameters can be combined:

https://yoursite.com/article?sesamy-login=true&sesamy-refresh=true&sesamy-debug=true

Processing Order:

  1. Debug settings applied first
  2. Cache operations (refresh)
  3. Authentication handlers (login, user)
  4. Token handlers (access_token, sesamy-token)
  5. Event handlers (purchase)

Error Handling

Handlers include built-in error handling:

javascript
// Handlers gracefully handle:
// - Malformed tokens
// - Expired tokens
// - Invalid parameters
// - Network errors

// Errors are logged when debug mode is enabled
// Failed handlers don't break page functionality

Common Integration Patterns

Post-Authentication Redirect

javascript
// Redirect to premium content after login
const checkout = await window.sesamy.checkouts.create({
  items: [{ sku: 'premium_monthly' }],
  redirectUrl: window.location.href + '?sesamy-refresh=true',
});
html
<!-- Require login for premium content -->
<a href="https://yoursite.com/exclusive?sesamy-login=true"> Read Exclusive Content </a>

<!-- Account-specific content -->
<a href="https://yoursite.com/account?sesamy-user={{ subscriber.email }}"> Your Account </a>

Debugging Setup

javascript
// Add debug toolbar for development
if (window.location.hostname === 'localhost') {
  const debugLink = document.createElement('a');
  debugLink.href = '?sesamy-debug=true';
  debugLink.textContent = '🐛 Enable Debug';
  debugLink.style.cssText = 'position:fixed;bottom:10px;right:10px;z-index:9999';
  document.body.appendChild(debugLink);
}
javascript
// Backend: Generate signed link
app.post('/api/generate-gift-access', async (req, res) => {
  const token = generateJWT({
    url: req.body.articleUrl,
    sku: req.body.sku,
    exp: Math.floor(Date.now() / 1000) + 86400, // 24h
  });

  res.json({
    shareUrl: `${req.body.articleUrl}?sesamy-token=${token}`,
  });
});

Troubleshooting

Parameters Not Working

Check:

  1. Sesamy JS is properly initialized
  2. Parameters are spelled correctly (case-sensitive)
  3. URL encoding is proper for special characters
  4. Browser console for error messages

Enable Debug Mode:

?sesamy-debug=true

Token Not Being Applied

Verify:

  • Token is valid JWT format
  • Token hasn't expired (check exp claim)
  • Token signature is valid
  • Token URL matches current page

Test:

javascript
// Manually decode and inspect token
const token = new URLSearchParams(window.location.search).get('sesamy-token');
const payload = JSON.parse(atob(token.split('.')[1]));
console.log('Token payload:', payload);
console.log('Token expired:', new Date(payload.exp * 1000) < new Date());

Authentication Redirect Loop

Possible Causes:

  • sesamy-login parameter not being removed
  • Authentication callback not handling tokens
  • Browser blocking cookies/localStorage

Solution:

javascript
// Check if login parameter is being cleaned
window.addEventListener('sesamyJsReady', () => {
  const hasLoginParam = new URLSearchParams(window.location.search).has('sesamy-login');
  console.log('Login param still present:', hasLoginParam); // Should be false
});

Reference

All Supported Parameters

ParameterLocationPurposeAuto-Remove
access_tokenHash (#)OAuth access token
sesamy-loginQuery (?)Force authentication
sesamy_loginQuery (?)Force authentication (legacy)
sesamy-userQuery (?)Specific user login
sesamy-tokenQuery (?)Signed access token
tokenQuery (?)Signed access token (fallback)
sesamy-purchaseQuery (?)Purchase completion
sesamy-refreshQuery (?)Clear cache
force-refetch-entitlementsQuery (?)Clear cache (deprecated)
sesamy-debugQuery (?)Enable/disable debug

Released under the MIT License.