btn.social

Guides

A collection of more in-depth walkthroughs for specialized questions.

Load TypeScript definitions

You will need to install the btn.social npm package.

$ npm install btn.social

When using the npm package, the TypeScript definitions will load automatically:

import * as btn from 'btn.social';
//           ^ type-aware~!

When using the web SDK, you may attach a TypeScript <reference/> to load the btn.social/web types:

/// <reference types="btn.social/web" />

declare global {
  var btnsocial: Window['btnsocial'];
}

export function onload(): void {
  btnsocial.onlogin(function (payload) {
    console.log('user logged in', payload);
  });
}

Link a Payload with a DB Record

Even though you may configure a Webhook for your application, the Webhook will process a Payload asynchronously. This may result in a race condition when a new user registers and then your client expects — and assumes — your server to have a database record for them already.

To combat this, you can define an onlogin callback that synchronously interacts with your API to ensure a record exists in the "users" table.

The example below assumes a single-page application (SPA) scenario. It uses the npm package (not required) to define an onlogin callback that will POST the successful Payload to a server-side "/api/whoami" URL endpoint.

At the same time, the onlogin handler interacts with (hypothetical) SPA “stores” to manage application state.

import * as btn from 'btn.social';
import { user } from './stores/user';
import { loading } from './stores/global';
import { route } from './lib/router';

// Callback for successful logins
btn.onlogin(async function (payload) {
  loading.set(true);
  // Forward data to own API server
  // ~> receive normalized/synchronized DB record
  let res = await fetch('/api/whoami', {
    method: 'POST',
    body: JSON.stringify(payload),
    headers: {
      'Content-Type': 'application/json'
    }
  });
  loading.set(false);

  if (res.ok) {
    let record = await res.json();
    //  ^ your DB normalized data
    user.set(record);

    // Assumed API data
    if (record.welcome) {
      route('/welcome');
    } else {
      route('/');
    }
  }
});