Browser SDK

The Nametag browser SDK allows you to add a signin button to your site which will allow your users to sign in or share data using Nametag without leaving your app.

For an example of a single page application that uses the browser SDK for sign in with ID, see HouseTonight on Github.

Caution: This feature is in beta. While we do not expect these interfaces to change, they might. If you have any issues, please report them to help@nametag.co.

Static approach

Use this approach to add a sign in button on static sites, or sites where you need a quick way to add an inline signin button.

Add the following snippet just above the </body> tag in your HTML:

<html>
  <body>
    <!-- your content here -->
    <script src="https://nametag.co/authorize.js"></script>
  </body>
</html>

Wherever you want to add a signin button, add the following:

<div data-nametag-button="signin"
     data-nametag-client-id="CLIENT_ID"
     data-nametag-redirect-uri="https://app.example.com/callback"
     data-nametag-scopes="login nt:legal_name nt:email"
     data-nametag-state="some_state_defined_by_your_app"
     data-nametag-button-variant="blue" />

The following data-nametag-* elements are recognized:

Attribute Value
data-nametag-button Must be signin. This attribute signals that this element should be a Nametag signin button.
data-nametag-client-id Your OAuth 2.0 client ID from the developer console.
data-nametag-redirect-uri The OAuth 2.0 redirect URI where the browser will be directed after the login.
data-nametag-scopes A space-separated list of the OAuth 2.0 scopes that you are requesting with this request. (Scopes must be defined in the developer console).
data-nametag-state (optional) The OAuth 2.0 state value. This value will be passed as a query argument to your redirect uri.
data-nametag-pkce (optional) Enable OAuth 2.0 PKCE mode, typically used for single page applications that don’t have access to the client secret. Valid values are true and false. (Default: false)
data-nametag-button-variant (optional) The visual appearance of the button. Valid values are blue, black and white. (Default: blue)
data-nametag-icon-position (optional) If left then the button icon will be left justified. If center then the icon will be in the center of the button near the text. (Default: left)

Note: You will need to implement a callback URL (redirect_uri). The user’s browser is sent to the callback URL when the authentication completes.

Custom button

If you attach the data-nametag-* elements to an empty element, you’ll get a default button. If you’d like to customize the button, place your customization insize the element, for example:

<div data-nametag-button="signin"
     data-nametag-client-id="CLIENT_ID"
     data-nametag-redirect-uri="https://app.example.com/callback"
     data-nametag-scopes="login nt:legal_name nt:email"
     data-nametag-state="some_state_defined_by_your_app"
     data-nametag-button-variant="blue" >
    <div>Your custom button here</div>
</div>

Advanced approach

For single page applications where the simple approach doesn’t provide enough flexibility, you can use the @nametag/browser package for more fine grained control.

Create an Auth object configured for your app (this is most common during app initialization):

import { Auth } from "@nametag/browser";

const nametag = new Auth({
  // get your client ID for your app from https://console.nametag.co
  client_id: "CLIENT_ID",

  // A valid callback URL listed in https://console.nametag.co
  redirect_uri: window.origin + "/oauth2/callback",

  pkce: true,  // for single page applications

  // optional. If you don't provide this, a random value will be used.
  state: "YOUR_APPS_STATE_DATA",

  // which data elements you are requesting
  scopes: ["login", "nt:email", "nt:legal_name"],
});

Add a placeholder element for the signin button. You can use nametag.SignedIn() to determine if the user has a valid session:

if (nametag.SignedIn()) {
  document.write('signed in!')
} else {
  document.write(`<div id="my-signin-button"></div>`)

  // turn placeholder element into an authorize button
  nametag.AuthorizeButton(document.getElementByID("my-signin-button"), {
    variant: "blue",
    icon_position: "left",
    popup_variant: "concise"
  })
}

When the user completes authorization, the browser will be sent to your redirect_uri. If you have enabled pkce mode, this will be a client-side route. Otherwise, you will handle this request on the server.

// handling the redirect_uri on the client with PKCE mode
async function windowLocationDidChange() {
   const res = await nametag.HandleCallback()
   if (res === null) {
     console.log("current location is not an OAuth 2.0 callback")
   } else if (res.error) {
     console.error("authorization failed:", err)
   } else if (res.token) {
     console.log("authorization success", res.token.subject)
   }
}

After the signin completes, you can fetch the data you requested and use them in your app. You can fetch properties only if they are defined in the developer console for your app, and if the user has approved sharing with you.

const props = await nametag.GetProperties(["nt:email", "nt:legal_name"]);
if (props && props.get("nt:legal_name")) {
    console.log(`Hello, ${props.get("nt:legal_name").value}!`)
}

When the user presses your signout button, destroy the session:

async function onSignOutPressed() {
  await nametag.SignOut();
}

Reference

Auth

The Auth object manages authorization settings for your app. It represents the authentication flow for a user.

Constructor

constructor(options: Options)

Create a new Auth object. options is an object which contains the following fields:

Field Type Description
client_id string The OAuth 2.0 client ID (get yours from Nametag)
redirect_uri string, optional The URL that the browser will be sent to after authentication
scopes Array <string > The OAuth 2.0 scopes you are requesting for this authorization. Scopes must a subset of those defined for your app in the Nametag.
state string Arbitrary data that you define for your application. This value is passed to your CallbackURL upon completion of the authorzation flow.
pkce boolean, optional Enable PKCE mode which is used for single page applications (default: true)
localStorage IStorage, optional An interface that is used to handle token storage. The default is window.localStorage.

Methods

AuthorizeURL

Builds a URL that will start the authentication flow. Redirect the user to the returned URL to start authentication. When authentication completes, the user will be redirected to your redirect_uri.

Note that authorization requests are valid for 168 hours (7 days) from their creation.

Arguments: (none)

Return value: Promise< string >

HandleCallback

Invoke this function when the user’s browser navigates to your redirect_uri in PKCE mode. This function extracts the OAuth 2.0 response parameters from the URL fragment in the current URL and, if the user authorized sharing, exchanges the code for a Token and stores it in the browser’s local storage.

After this call successfully completes, SignedIn will return true, and Token will return a non-null value.

If the current URL fragment represents an OAuth 2.0 redirect URI, this function returns an object describing the result. Otherwise, it returns null.

Note: this function makes sense only in PKCE mode. It throws an exception if called when PKCE is not used.

Arguments: (none)

Return value: Promise<HandleCallbackResult | null>

HandleCallbackResult has the following fields:

Field Type Description
error string, optional The OAuth 2.0 error message, if authorization was not completed.
token Token, optional The OAuth 2.0 token response, if authorization was completed.

Note: exactly one of error or token will be defined.

SignOut

Removes the credential stored in the brower’s local storage.

Note: this function makes sense only in PKCE mode. It throws an exception if called when PKCE is not used.

Arguments: (none)

Return value: (none)

SignedIn

Check the authentication status of the user. Returns true if the user has completed an authentication, or false otherwise.

Note: this function makes sense only in PKCE mode. It throws an exception if called when PKCE is not used.

Arguments: (none)

Return value: boolean

Token

Returns the current user’s authorization token, or null if the user is not signed in.

Note: this function makes sense only in PKCE mode. It throws an exception if called when PKCE is not used.

Arguments: (none)

Return value: Token | null

WatchToken

Invoke a callback whenever the current user’s authorization token is updated.

Note: this function makes sense only in PKCE mode. It throws an exception if called when PKCE is not used.

Arguments:

  • callback (function (Token | null) - A callback to be invoked with the token, whenever it changes.

Return value:

  • TokenWatch - an object representing the active watcher, which can be used to close the watcher when you are finished with it.
GetProperties

Fetch properties for a signed in user. Returns null if the user is not logged in or if an error occurs.

Note: this function makes sense only in PKCE mode. It throws an exception if called when PKCE is not used.

Arguments:

  • scopes (Array<string>) - a list of scopes for which you’d like values, e.g. ["nt:legal_name"].

Return value:

AuthorizeButton

Builds an authorization button.

Arguments:

  • element (HTMLElement) - the element where the button should be attached.
  • options (AuthorizeButtonOptions, optional)

AuthorizeButtonOptions has the following fields:

Field Type Description
variant string the color of the button. Options are "blue", "black", or "white"
icon_position string the position of the Nametag icon. If "center" then the icon is positioned close to the button text. If "left" the icon is left justified inside the button. Default: "left".

Return value: (none)

Token

Represents an OAuth 2.0 token response with Nametag’s own extensions.

Field Type Description
id_token string An OIDC-compatible JWT that identifies the user, suitable for use as a user authentication token
access_token string A field required OAuth 2.0 compliance, but not otherwise used.
refresh_token string A field required OAuth 2.0 compliance, but not otherwise used.
scope string A space-separated list of the scopes that have been approved. (Note that the format of this field differs from the Auth’s scopes field. This is required for OAuth 2.0 compliance.
expires_in number The lifetime of the id_token, in seconds.
subject string An opaque identifier for the authenticated user.

Properties

The Properties object represents the value returned from GetProperties

Field Type Description
subject string the opaque, unique identifier for the authenticated user.
properties Array<Property> the property data.

Methods

get

Fetch the data for a specific scope

Arguments:

  • scope (string) - the scope to fetch

Return value: Property | null

Property

Represents a single property that contains data for a particular scope

Fields

Field Type Description
scope string the scope of this data field
status 200 or 403 the sharing status of the data item. If this value is 200 then the data is shared with your app. If the value is 403 then the data has not been shared, has been revoked, or has expired.
value any the value of the scope. The type of this value depends on the requested scope, but is most commonly a string. If status is not 200 then this field will not be present.
expires Date the time when the user’s authorization expires. If status is not 200 then this field will not be present.

IStorage

An interface that defines browser-local storage. By default this is window.localStorage but you can replace it with your own implementation if you’d like to handle storage differently. This interface is a subset of Storage.

Methods

The following methods from Storage must be defined to satisfy this interface:

TokenWatch

The type returned from WatchToken.

Methods

close

Stop watching for token changes

Arguments: (none)

Return value: (none)