NewFans API, previously OnlyFans API · A new name. A broader platform.
Fans API

Quick Start

Get started with @onlyfansapi/auth in minutes

Overview

This guide will walk you through implementing @onlyfansapi/auth in your application. The authentication library provides a simple, secure way to authenticate users with their OnlyFans accounts.

Before You Start

Make sure you've completed the installation steps first. You'll need:

  • The package installed in your project
  • An API key to create client session tokens
  • A client session token (starts with ofapi_cs_) to use with the library

Watch the connect and reconnect walkthrough for server code, browser code, and both popup flows.

Basic Usage

Use startOnlyFansAuthentication to connect a new account, or updateOnlyFansCredentials to update credentials on an existing account. Both use the same authentication flow. When called, it opens a secure iframe modal where users can authenticate with their OnlyFans account.

Import

import {  } from '@onlyfansapi/auth';

Function Signature

const startOnlyFansAuthentication: (clientSessionToken: string, options: {
    onSuccess: (data: AuthSuccessData) => void;
    onError: (error: AuthFailureError) => void;
    onContinue?: () => void;
}) => void

Parameters:

  • clientSecret (string, required): Your client session token obtained from the Create Client Session API endpoint
  • options.onSuccess (function, required): Callback invoked when authentication succeeds
  • options.onError (function, required): Callback invoked when authentication fails

Reconnect an existing account

Use updateOnlyFansCredentials(clientSessionToken, options) when an account disconnects or its login details change. Your backend creates a fresh client session with only the existing account ID:

{ "account_id": "acct_XXXXXXXXXX" }

Your backend must authorize the signed-in user's access to that account before requesting the token. Return data.token to the frontend:

import { updateOnlyFansCredentials } from '@onlyfansapi/auth';

updateOnlyFansCredentials(token, {
  onSuccess: ({ accountId, username, onlyfansData }) => {
    // Refresh the existing account. Do not create a second connection.
    refreshAccount(accountId);
  },
  onError: ({ message }) => showError(message),
});

Script-tag integrations use window.FansAPI.Auth.updateOnlyFansCredentials(token, options). The legacy window.OnlyFansAPI.Auth namespace also supports it. Options, callbacks, and closeOnlyFansAuthentication() are shared with the original method.

The popup prefills an editable saved email and leaves the password empty. If no email is saved, both fields start empty. It preserves the account ID, OnlyFans profile identity, granted permissions, name, and proxy. Signing in to another OnlyFans profile is rejected; changing the login email for the same profile is allowed.

Opening the popup does not change the account. Submitting saves the new credentials immediately and interrupts access until login succeeds. If login fails, the submitted credentials remain saved. Try again retains the email, clears the password field, and never deletes the account.

Closing after submission does not cancel login. Reopen the same token to resume progress or verification. Duplicate submissions follow the existing attempt; a competing session shows "Authentication already in progress."

Tokens allow submissions and retries for 30 minutes from creation. Already-started attempts can finish within their normal authentication deadline. After success, another update needs a new token. New attempts are limited to three per account per minute; a 429 response includes Retry-After: 60.

The Re-authenticate Account endpoint retries saved credentials without collecting replacements. For server-side replacement, use Update Authentication Credentials.

Framework Examples

import React, { useState } from 'react';
import { startOnlyFansAuthentication } from '@onlyfansapi/auth';

export default function AuthComponent() {
  const [isLoading, setIsLoading] = useState(false);
  const [authData, setAuthData] = useState(null);
  const [error, setError] = useState(null);

  const handleAuthentication = () => {
    setIsLoading(true);
    setError(null);
    
    startOnlyFansAuthentication('ofapi_cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', {
      onSuccess: (data) => {
        console.log('Authentication successful:', data);
        setAuthData(data);
        setIsLoading(false);
        // data.accountId - The authenticated account ID
        // data.username - The authenticated username
        // data.response - Full response from the API
      },
      onError: (error) => {
        console.error('Authentication failed:', error);
        setError(error);
        setIsLoading(false);
        // error.message - Error message
        // error.code - Error code (if available)
        // error.details - Additional error details (if available)
      },
    });
  };

  return (
    <div className="auth-container">
      <button 
        onClick={handleAuthentication}
        disabled={isLoading}
        className="auth-button"
      >
        {isLoading ? 'Authenticating...' : 'Connect OnlyFans Account'}
      </button>
      
      {authData && (
        <div className="success-message">
          <h3>Authentication Successful!</h3>
          <p>Account ID: {authData.accountId}</p>
          <p>Username: {authData.username}</p>
        </div>
      )}
      
      {error && (
        <div className="error-message">
          <h3>Authentication Failed</h3>
          <p>{error.message}</p>
        </div>
      )}
    </div>
  );
}
<template>
  <div class="auth-container">
    <button 
      @click="handleAuthentication"
      :disabled="isLoading"
      class="auth-button"
    >
      {{ isLoading ? 'Authenticating...' : 'Connect OnlyFans Account' }}
    </button>
    
    <div v-if="authData" class="success-message">
      <h3>Authentication Successful!</h3>
      <p>Account ID: {{ authData.accountId }}</p>
      <p>Username: {{ authData.username }}</p>
    </div>
    
    <div v-if="error" class="error-message">
      <h3>Authentication Failed</h3>
      <p>{{ error.message }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { startOnlyFansAuthentication } from '@onlyfansapi/auth';

const isLoading = ref(false);
const authData = ref(null);
const error = ref(null);

const handleAuthentication = () => {
  isLoading.value = true;
  error.value = null;
  
  startOnlyFansAuthentication('ofapi_cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', {
    onSuccess: (data) => {
      console.log('Authentication successful:', data);
      authData.value = data;
      isLoading.value = false;
    },
    onError: (err) => {
      console.error('Authentication failed:', err);
      error.value = err;
      isLoading.value = false;
    },
  });
};
</script>
<script>
  import { startOnlyFansAuthentication } from '@onlyfansapi/auth';

  let isLoading = false;
  let authData = null;
  let error = null;

  function handleAuthentication() {
    isLoading = true;
    error = null;
    
    startOnlyFansAuthentication('ofapi_cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', {
      onSuccess: (data) => {
        console.log('Authentication successful:', data);
        authData = data;
        isLoading = false;
      },
      onError: (err) => {
        console.error('Authentication failed:', err);
        error = err;
        isLoading = false;
      },
    });
  }
</script>

<div class="auth-container">
  <button 
    on:click={handleAuthentication}
    disabled={isLoading}
    class="auth-button"
  >
    {isLoading ? 'Authenticating...' : 'Connect OnlyFans Account'}
  </button>
  
  {#if authData}
    <div class="success-message">
      <h3>Authentication Successful!</h3>
      <p>Account ID: {authData.accountId}</p>
      <p>Username: {authData.username}</p>
    </div>
  {/if}
  
  {#if error}
    <div class="error-message">
      <h3>Authentication Failed</h3>
      <p>{error.message}</p>
    </div>
  {/if}
</div>
import { Component } from '@angular/core';
import { startOnlyFansAuthentication } from '@onlyfansapi/auth';

@Component({
  selector: 'app-auth',
  template: `
    <div class="auth-container">
      <button 
        (click)="handleAuthentication()"
        [disabled]="isLoading"
        class="auth-button"
      >
        {{ isLoading ? 'Authenticating...' : 'Connect OnlyFans Account' }}
      </button>
      
      <div *ngIf="authData" class="success-message">
        <h3>Authentication Successful!</h3>
        <p>Account ID: {{ authData.accountId }}</p>
        <p>Username: {{ authData.username }}</p>
      </div>
      
      <div *ngIf="error" class="error-message">
        <h3>Authentication Failed</h3>
        <p>{{ error.message }}</p>
      </div>
    </div>
  `
})
export class AuthComponent {
  isLoading = false;
  authData: any = null;
  error: any = null;

  handleAuthentication() {
    this.isLoading = true;
    this.error = null;
    
    startOnlyFansAuthentication('ofapi_cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', {
      onSuccess: (data) => {
        console.log('Authentication successful:', data);
        this.authData = data;
        this.isLoading = false;
      },
      onError: (error) => {
        console.error('Authentication failed:', error);
        this.error = error;
        this.isLoading = false;
      },
    });
  }
}
<!DOCTYPE html>
<html>
<head>
  <title>Fans API Auth</title>
</head>
<body>
  <div class="auth-container">
    <button id="auth-button" class="auth-button">
      Connect OnlyFans Account
    </button>
    
    <div id="success-message" style="display: none;">
      <h3>Authentication Successful!</h3>
      <p id="account-id"></p>
      <p id="username"></p>
    </div>
    
    <div id="error-message" style="display: none;">
      <h3>Authentication Failed</h3>
      <p id="error-text"></p>
    </div>
  </div>

  <script type="module">
    import { startOnlyFansAuthentication } from '@onlyfansapi/auth';

    const authButton = document.getElementById('auth-button');
    const successMessage = document.getElementById('success-message');
    const errorMessage = document.getElementById('error-message');

    authButton.addEventListener('click', () => {
      authButton.disabled = true;
      authButton.textContent = 'Authenticating...';
      errorMessage.style.display = 'none';
      
      startOnlyFansAuthentication('ofapi_cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', {
        onSuccess: (data) => {
          console.log('Authentication successful:', data);
          document.getElementById('account-id').textContent = 
            'Account ID: ' + data.accountId;
          document.getElementById('username').textContent = 
            'Username: ' + data.username;
          successMessage.style.display = 'block';
          authButton.disabled = false;
          authButton.textContent = 'Connect OnlyFans Account';
        },
        onError: (error) => {
          console.error('Authentication failed:', error);
          document.getElementById('error-text').textContent = error.message;
          errorMessage.style.display = 'block';
          authButton.disabled = false;
          authButton.textContent = 'Connect OnlyFans Account';
        },
      });
    });
  </script>
</body>
</html>

Response Data

The library provides TypeScript types for better type safety. Import them if needed:

import type { AuthSuccessData, AuthError } from '@onlyfansapi/auth';

Success Response

When authentication is successful, the onSuccess callback receives an AuthSuccessData object:

interface AuthSuccessData {
  accountId: string;    // The authenticated OnlyFans account ID
  username: string;     // The authenticated OnlyFans username
  response: object;     // Full response object from the API containing additional metadata
}

Example usage:

onSuccess: (data) => {
  // Store the account ID for future API requests
  localStorage.setItem('ofAccountId', data.accountId);
  
  // Redirect to dashboard or update UI
  console.log(`Authenticated as ${data.username}`);
}

Error Response

When authentication fails, the onError callback receives an AuthError object:

interface AuthError {
  message: string;       // Human-readable error message
  code?: string;        // Error code (if available) for programmatic handling
  details?: object;     // Additional error details (if available)
}

Common error scenarios:

  • User cancels the authentication flow
  • Network connectivity issues
  • Invalid or expired client session token
  • OnlyFans account access issues

Example error handling:

onError: (error) => {
  if (error.code === 'AUTH_CANCELLED') {
    // User closed the authentication modal
    console.log('Authentication cancelled by user');
  } else {
    // Handle other errors
    console.error('Authentication failed:', error.message);
    // Display error to user
  }
}

Security

The authentication library implements multiple security measures to protect user data:

  • Origin validation: All communication with the authentication iframe is validated by origin
  • Domain whitelisting: Only messages from the configured Fans API domain are accepted
  • Secure token transmission: Client session tokens are passed securely via URL parameters
  • HTTPS required: The library requires HTTPS connections in production environments

Best Practices

Storing Client Session Tokens

Fetch a fresh client session token from your backend for the selected account and current user. Keep API keys on your server. Do not use a shared token in NEXT_PUBLIC_* environment variables or hardcode one in your frontend.

const response = await fetch('/api/accounts/reconnect', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ accountId }),
});
if (!response.ok) throw new Error('Unable to open reconnect dialog');
const { token } = await response.json();

Error Handling

Always handle both success and error cases:

startOnlyFansAuthentication("clientSecret", {
  onSuccess: (data) => {
    // Update your application state
    // Persist authentication data if needed
    // Redirect or update UI
  },
  onError: (error) => {
    // Log errors for debugging
    // Show user-friendly error messages
    // Provide fallback options
  },
});

User Experience

  • Show a loading state while authentication is in progress
  • Disable the authentication button during the flow to prevent duplicate requests
  • Provide clear feedback on success or failure
  • Consider adding a "try again" option if authentication fails

Troubleshooting

Common Issues

Authentication modal doesn't open:

  • Ensure your client session token is valid and properly formatted
  • Check browser console for any error messages
  • Verify that pop-ups aren't blocked by your browser

"Invalid client secret" error:

  • Verify your client session token is correct (starts with ofapi_cs_)
  • Check that the token hasn't expired
  • Ensure you're using a token created via the Create Client Session API

Network errors:

  • Check your internet connection
  • Verify Fans API is accessible from your network
  • Some corporate firewalls may block the authentication iframe

Next Steps

On this page