# Userfront core JS library

The Userfront core JavaScript library is intended for use in frontend applications.

It can be used for the following:

# Setup

Note

The core library must always be initialized with an account or tenant ID using the init() method.

# init (tenantId)

Initializes the Userfront core library with your account or tenant ID.

import Userfront from "@userfront/core";

Userfront.init("demo1234");

# addInitCallback (function)

Calls the supplied callback whenever Userfront.init() is called. A JSON object with the tenantId is supplied to the callback.

If addInitCallback is called more than once, callbacks are called in the order they were added (first added = first called).

Once Userfront.init() is called, the callbacks are reset and are not called on subsequent Userfront.init() calls.

import Userfront, { addInitCallback } from "@userfront/core";

addInitCallback((data) => console.log(data));
addInitCallback(console.log("Again"));

Userfront.init("demo1234");

// => { tenantId: "demo1234" }
// => Again

Userfront.init("demo1234");

// No callbacks

# Authentication

# signup (options)

Registers a new user with one of the available methods.

Option Description
method The method for registering. Options are: password, passwordless, verificationCode, apple, azure, facebook, github, google, or linkedin. See below for more info on methods. See below for more info on methods.
email The user's email address, which is required for the password and passwordless methods.
phoneNumber The user's phone number, which is required for the verificationCode method when using the sms channel.
username The user's username (optional). Used only with the password and passwordless methods.
name The user's name (optional). Used only with the password and passwordless methods.
data The user's custom data object (optional). Used only with the password and passwordless methods.
password The user's password. Used only with the password.
redirect Manually set the path to redirect to, or false to prevent redirection.

# Signup via password method

Submits an email and password to create a user.

Upon success, receives JWT access token and adds the JWT access token to the browser's cookies, then redirects the browser to the After-signup path.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Example with email
Userfront.signup({
  method: "password",
  email: "user@example.com",
  password: "testmodepassword",
});

// Example with name and username included
Userfront.signup({
  method: "password",
  email: "user@example.com",
  name: "Jane Doe",
  username: "jdoe11",
  data: {
    custom: "information",
  },
  password: "testmodepassword",
});
Return values

# Signup via passwordless method

Creates a user and sends them an email with a link to log in. This link works with the Login via link method.

If a user with the given email address already exists, sends them an email to log in.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Example with email
Userfront.signup({
  method: "passwordless",
  email: "user@example.com",
});

// Example with name and username included
Userfront.signup({
  method: "passwordless",
  email: "user@example.com",
  name: "Jane Doe",
  username: "jdoe11",
  data: {
    custom: "information",
  },
});
Return values

# Signup via verificationCode method

This method creates a new user and sends them a 6-digit verificationCode by SMS or email.

If a user with the given phone number or email address already exists, it sends them a 6-digit verification code to log in.

This verification code works with the Login via verificationCode method.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Sign up with SMS verificationCode (default)
Userfront.signup({
  method: "verificationCode",
  channel: "sms",
  phoneNumber: "+15558675309",
  name: "John Doe",
  username: "jdoe11",
  email: "user@example.com",
  data: {
    custom: "information",
  },
});

// Sign up with email verificationCode
Userfront.signup({
  method: "verificationCode",
  channel: "email",
  email: "user@example.com",
  data: {
    custom: "information",
  },
});
Return values

# Signup via apple, azure, facebook, github, google, or linkedin methods


Initiates the sign-on flow for a given SSO provider.

Note

When using SSO, there is no difference between the signup and login methods.

Both methods initiate the sign-on flow:

  • New users are ultimately redirected to your After-signup path
  • Existing users are ultimately redirected to your After-login path.
import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Example with GitHub
Userfront.signup({ method: "github" });

// Example with Google
Userfront.signup({ method: "google" });

# login (options)

Initiates a login for a user with one of the available methods.

Option Description
method The method for logging in. Options are: password, passwordless, link, totp, verificationCode, apple, azure, facebook, github, google, linkedin, and saml. See below for more info on methods.
email The user's email. Used with the password and passwordless methods.
username The user's username. Used only with the password method.
emailOrUsername The user's email or username. Used only with the password method.
password The user's password. Used only with the password method.
token The token= URL parameter sent in a login link. Used only with the link method.
uuid The uuid= URL parameter sent in a login link. Used only with the link method.
totpCode A one-time code generated by a TOTP authenicator device. Used only with the totp method.
backupCode A single-use backup code to be used in place of the totpCode if a TOTP authenticator device is lost. Used only with the totp method.
verificationCode A 6-digit code sent by email or SMS. Used only with verificationCode method.
redirect Manually set the path to redirect to, or false to prevent redirection.

# Login via password method

This method is used to log in with a password along with an email or username.

Sends a username or email along with a password in order to receive a JWT access token, then adds the JWT access token to the browser's cookies and redirects the browser to the After-login path.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Example with email
Userfront.login({
  method: "password",
  email: "user@example.com",
  password: "testmodepassword",
});

// Example with username
Userfront.login({
  method: "password",
  username: "janedoe",
  password: "testmodepassword",
});

// Example with emailOrUsername
Userfront.login({
  method: "password",
  emailOrUsername: "user@example.com", // or "janedoe"
  password: "testmodepassword",
});
Return values

# Login via passwordless method

This method is used to send the user a magic/passwordless login link.

Sends the user an email with a link to log in. This link works with the Login via link method.

Note

If no user exists with the given email, this method creates a new user and sends them a login link.

See also: signup via passwordless method.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Send a login link email
Userfront.login({
  method: "passwordless",
  email: "user@example.com",
});
Return values

This method is used to read the URL query parameters token and uuid that are sent with login link emails, and uses these parameters to log in a user.

Sends the token and uuid in order to receive JWT access token, then adds the JWT access token to the browser's cookies and redirects the browser to the After-login path.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Read token & uuid from the URL
Userfront.login({ method: "link" });

// Pass token & uuid explicitly
Userfront.login({
  method: "link",
  token: "34765497-f806-4be2-a32e-26df63ce9f7f",
  uuid: "9994b8d1-d51b-4a83-aa85-7e7508b92525",
});
Return values

# Login via totp method

This method is used to pass a one-time totpCode generated by the user's TOTP authenticator device.

The user.getTotp() method allows a user to pair their TOTP authenticator device to generate codes.

# Backup codes

When a user pairs their TOTP authenticator device with user.getTotp(), the response also returns an array of single-use backup codes.

These backupCodes can be used once each, to log in without a totpCode in case their TOTP authenticator device is lost.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Log in with totpCode
Userfront.login({
  method: "totp",
  emailOrUsername: "user@example.com",
  totpCode: "123456",
});

// Log in with backupCode
Userfront.login({
  method: "totp",
  emailOrUsername: "user@example.com",
  backupCode: "aaaaa-bbbbb",
});
Return values

# Login via verificationCode method

This method is used to log in with a 6-digit verificationCode.

Sends the channel, phoneNumber (or email), and verificationCode in order to receive a JWT access token, then adds the JWT access token to the browser's cookies and redirects the browser to the After-login path.

See the sendVerificationCode() method to send the user a verification code by sms or email.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Log in with SMS verificationCode (default)
Userfront.login({
  method: "verificationCode",
  channel: "sms",
  phoneNumber: "+15558675309",
  verificationCode: "123456",
});

// Log in with email verificationCode
Userfront.login({
  method: "verificationCode",
  channel: "email",
  email: "user@example.com",
  verificationCode: "123456",
});
Return values

# Login via apple, azure, facebook, github, google, or linkedin methods


Initiates the sign-on flow for a given SSO provider.

Note

When using SSO, there is no difference between the signup and login methods.

Both methods initiate the sign-on flow:

  • New users are ultimately redirected to your After-signup path
  • Existing users are ultimately redirected to your After-login path.
import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Example with GitHub
Userfront.login({ method: "github" });

// Example with Google
Userfront.login({ method: "google" });

# Login via saml method


Completes the sign-on flow for a SAML service provider.

Obtains a SAML token and redirects the browser to the Userfront API SAML login endpoint where the login response will be sent to the service provider who initiated the SAML login request.

When a user clicks a link to log in to a service provider, the service provider sends a SAML login request to the Userfront API which will then redirect the browser to your After-logout path (opens new window) where this method should be called.

Note

When using the saml method, there is no difference between signing the user in and signing the user up.

Both cases are handled by the service provider during the sign-on flow:

  • New users are redirected to the service provider's signup process.
  • Existing users will be redirected to the service provider's path after logging in.
import Userfront from "@userfront/core";
Userfront.init("demo1234");

Userfront.login({ method: "saml" });

# Login via mfa method

Completes the login process using an MFA verification code.

Note

Requires MFA to be enabled for tenant.

MFA is currently in beta. If you would like to enable it for your account, please contact us using the chat in the bottom-right.

Property Type Description
firstFactorCode String The string identifier obtained from the login() response to complete MFA login - see sendSms() for more information.
verificationCode String The verification code sent to the user's device.
import Userfront from "@userfront/core";
Userfront.init("demo1234");

Userfront.login({
  method: "mfa",
  firstFactorCode: "a9c9b41c-ce76-4f7e-915a-abf18a36a4ae",
  verificationCode: "123456",
});
Return values

# logout (options)

Initiates logout for a user.

Option Description
redirect Manually set the path to redirect to, or false to prevent redirection.
method The method for logging out. Currently only used for SAML.

# Default logout()

Logs a user out by invalidating their session, removes JWT access token from the browser, and then redirects the browser to the After-logout path.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Log out a user
Userfront.logout();

// Log out a user without redirecting
Userfront.logout({ redirect: false });
Return values

# Log out of SAML service provider

Completes the SAML logout process.

Obtains a SAML token and redirects the browser to the SAML logout endpoint where the logout response will be sent to the service provider who initiated the SAML logout request.

When a user wants to log out of a service provider, the service provider sends a SAML logout request to the Userfront API which will then redirect the browser to your After-logout path (opens new window) where this method should be called.

Upon successful logout, the user will be logged out of the service provider yet remain logged in to your tenant's application.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Complete log out process for service provider
Userfront.logout({ method: "saml" });

# redirectIfLoggedIn ()

Checks if the user is logged in and, if so, redirects the browser to the After-login path.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

Userfront.redirectIfLoggedIn();

# resetPassword (options)

Reset a user's password with the reset link credentials (token and uuid).

Uses the reset link credentials (token and uuid) to reset the user's password, then logs the user in by adding their JWT access token to the browser's cookies, and finally redirects the browser to the After-login path.

If the user does not have a password yet, then their password is created.

Option Description
password The new password to set for the user.
token The token= URL parameter sent in the password reset link.
uuid The uuid= URL parameter sent in the password reset link.
redirect Manually set the path to redirect to, or false to prevent redirection.
import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Read token & uuid from the URL
Userfront.updatePassword({
  password: "myshinynewpassword",
});

// Pass token & uuid explicitly
Userfront.updatePassword({
  password: "myshinynewpassword",
  token: "34765497-f806-4be2-a32e-26df63ce9f7f",
  uuid: "9994b8d1-d51b-4a83-aa85-7e7508b92525",
});
Return values

Sends an email containing a login link. This link directs the user to the After-logout path, where the login form should be located.

The user in question must exist already.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

Userfront.sendLoginLink("user@example.com");
Return values

Sends an email containing a password reset link. This link directs the user to the Password reset path.

The password reset link contains the token and uuid credentials, which can be used with the updatePassword method.

The user in question must exist already.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

Userfront.sendResetLink("user@example.com");
Return values

# sendVerificationCode (options)

Sends an SMS or email containing a 6-digit verification code.

The verification code can be used with the Login via verificationCode method.

If the user does not exist yet, a new record is created.

Option Description
channel "sms" (default) or "email"
phoneNumber The user's phone number. Required when using the sms channel.
email The user's email address. Required when using the email channel or if registering a new user.
username The user's username (optional). Used if registering a new user.
name The user's name (optional). Used if registering a new user.
data The user's custom data object (optional). Used if registering a new user.
import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Send verification code by SMS (default)
Userfront.sendVerificationCode({
  channel: "sms",
  phoneNumber: "+15558675309",
});

// Send verification code by email
Userfront.sendVerificationCode({
  channel: "email",
  email: "user@example.com",
});
Return values

# sendSms (options)

Sends an SMS to a phone number.

Option Description
type The type of SMS to send. Currently the only option is mfa. See below for more info.
to The phone number where the SMS should be sent. The phone number should be in E.164 format.

E.164 numbers are formatted [+] [country code] [subscriber number including area code] and can have a maximum of fifteen digits. e.g. +15558675309
firstFactorCode A string identifier obtained from the login() response to complete MFA login.

The firstFactorCode parameter is obtained in the response of login() when MFA is enabled for your tenant:

{
  "message": "OK",
  "result": {
    "mode": "live",
    "firstFactorCode": "304a8def-651c-4ab2-9ca0-1e3fca9e280a",
    "allowedStrategies": ["verificationCode"],
    "allowedChannels": ["sms"]
  }
}

# Send SMS via type verificationCode

Sends an SMS containing an MFA verification code to the phone number provided.

Note

Requires MFA to be enabled for tenant.

MFA is currently in beta. If you would like to enable it for your account, please contact us using the chat in the bottom-right.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

Userfront.sendSms({
  type: "verificationCode",
  to: "+15558675309",
  firstFactorCode: "a9c9b41c-ce76-4f7e-915a-abf18a36a4ae",
});
Return values

# User

# user

Returns information about the currently logged in user.

Note

Userfront.user is intended for frontend use only, to help you display information about the user.

Property Type Description
email String
name String Full name
image String Image URL
data Object Custom JSON data object
username String
confirmedAt String When the user confirmed their email
isConfirmed Boolean Whether the user has confirmed their email
createdAt String When the user record was created
updatedAt String When the user record was last updated
mode String live or test mode
tenantId String
userId Integer
userUuid String (UUID)
import Userfront from "@userfront/core";
Userfront.init("demo1234");

Userfront.user;

/** =>
 * {
 *    email: "jane@example.com",
 *    name: "Jane Example",
 *    image: "https://res.cloudinary.com/component/image/upload/avatars/avatar-plain-9.png",
 *    data: {
 *      value: "anything-you-want",
 *      custom: {
 *        value: "custom-value"
 *      }
 *    },
 *    username: "jane-example",
 *    confirmedAt: "2020-01-01T00:00:00.000Z",
 *    isConfirmed: true,
 *    createdAt: "2020-01-01T00:00:00.000Z",
 *    updatedAt: "2020-01-01T00:00:00.000Z",
 *    mode: "test",
 *    tenantId: "demo1234",
 *    userId: 1,
 *    userUuid: "d6f0f045-f6ea-4262-8724-dfc0b77e7dc9",
 * }
 */

# user.update (options)

Sends a request to update the currently logged in user.

The following user attributes are editable:

Property Type
name String
image String
username String
data Object
import Userfront from "@userfront/core";
Userfront.init("demo1234");

Userfront.user.update({
  name: "John Example",
  data: {
    somethingCustom: true,
  },
});

# user.updatePassword (options)

Updates a user's password while they are logged in.

If the user has a password already, the existingPassword field must be correct.

If the user does not have a password yet (e.g. if they signed up with SSO), the existingPassword field is ignored, and the password field is set directly.

Option Description
password The new password to set for the user.
existingPassword The user's existing password. Ignored if they do not have an existing password.
method If not defined, user.updatePassword first checks for reset link credentials (token and uuid), then checks the user's JWT access token. To skip checking for reset link credentials, specify { method: "jwt" }
import Userfront from "@userfront/core";
Userfront.init("demo1234");

// Update a user's password while logged in
Userfront.user.updatePassword({
  password: "myshinynewpassword",
  existingPassword: "mydulloldpassword",
});
Return values

# user.getTotp ()

Reads TOTP credentials for the currently logged in user, allowing them to pair a TOTP authenticator device to their account.

Once a device is paired, users can generate codes to Login via TOTP method.

# QR code

The qrCode attribute is the URL for a png image that can be displayed directly to the user.

<img src="data:image/png;base64,iVBORw0KG..." />

# Backup codes

Each user initially begins with 10 single-use backup codes for TOTP.

You should display these backup codes to the user so that they can store them in case they lose access to their authenticator device.

If all 10 single-use backup codes are used, the user will have to re-pair their authenticator device, at which time they will receive 10 new codes.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

Userfront.user.getTotp();
Return values

# user.hasRole (roleName, options)

Helper method to determine if the logged in user has a given role in the authorization object of their JWT access token.

Returns true if the role is present, or false if not present.

Note

user.hasRole() should only be used to show or hide public elements like buttons or badges.

Sensitive information should always rely on server-side checks.

Option Description
tenantId The tenant to check against. Defaults to the tenantId from Userfront.init(tenantId)
import Userfront from "@userfront/core";
Userfront.init("demo1234");

/**
 * {
 *   ...
 *   authorization: {
 *     demo1234: {
 *       roles: ["admin"]
 *     },
 *     abcd1234: {
 *       roles: ["custom role"]
 *     },
 *   }
 * }
 */

// Check for a role in demo1234 tenant
Userfront.user.hasRole("admin");
// => true
Userfront.user.hasRole("member");
// => false

// Check for a role in abcd1234 tenant
Userfront.user.hasRole("custom role", {
  tenantId: "abcd1234",
});
// => true

# Tokens

# tokens.accessToken

Returns the JWT access token.

Your frontend application can send the access token to your server in order to authenticate a user and provide information about their access levels. For more information, see Tokens & Access.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

Userfront.tokens.accessToken;

// => "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJtb2RlIjoidGVzdCIsImlzQ29uZmlybWVkIjp0cnVlLCJ1c2VySWQiOjEsInVzZXJVdWlkIjoiZDAwNTlmN2UtYzU0OS00NmYzLWEzYTMtOGEwNDY0MDkzZmMyIiwidGVuYW50SWQiOiJwOW55OGJkaiIsInNlc3Npb25JZCI6IjRlZjBlMjdjLTI1NDAtNDIzOS05YTJiLWRkZjgyZjE3YmExYiIsImF1dGhvcml6YXRpb24iOnsicDlueThiZGoiOnsidGVuYW50SWQiOiJwOW55OGJkaiIsIm5hbWUiOiJVc2VyZnJvbnQiLCJyb2xlcyI6WyJhZG1pbiJdLCJwZXJtaXNzaW9ucyI6W119fSwiaWF0IjoxNjE3MTQ4MDY3LCJleHAiOjE2MTk3NDAwNjd9.gYz4wxPHLY6PNp8KPEyIjLZ8QzG3-NFJGPitginuLaU"

# tokens.accessTokenName

Returns the name of the cookie that holds the JWT access token.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

Userfront.tokens.accessTokenName;

// => "access.demo1234"

# tokens.idToken

Note

The ID token is not intended for authentication or access control.

It is used client-side as a verifiable copy of the user's data. Typically it is easier to reference the user object instead.

Returns the JWT ID token.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

Userfront.tokens.idToken;

// => "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJtb2RlIjoidGVzdCIsInRlbmFudElkIjoicDlueThiZGoiLCJ1c2VySWQiOjEsInVzZXJVdWlkIjoiZDAwNTlmN2UtYzU0OS00NmYzLWEzYTMtOGEwNDY0MDkzZmMyIiwiZW1haWwiOiJhZG1pbkBleGFtcGxlLmNvbSIsImlzQ29uZmlybWVkIjp0cnVlLCJ1c2VybmFtZSI6ImFkbWluIiwibmFtZSI6IkFkbWluIFVzZXIiLCJpbWFnZSI6Imh0dHBzOi8vcmVzLmNsb3VkaW5hcnkuY29tL2NvbXBvbmVudC9pbWFnZS91cGxvYWQvYXZhdGFycy9hdmF0YXItMDcucG5nIiwiZGF0YSI6eyJjdXN0b20iOiJkYXRhIn0sImNvbmZpcm1lZEF0IjoiMjAyMC0wOS0xMVQyMTo1MjoyOC44MjBaIiwiY3JlYXRlZEF0IjoiMjAyMC0wOS0xMVQyMTo1MjoyOC4wOTVaIiwidXBkYXRlZEF0IjoiMjAyMS0wMy0yNFQyMDo1MzowMi4zMDVaIiwic2Vzc2lvbklkIjoiNGVmMGUyN2MtMjU0MC00MjM5LTlhMmItZGRmODJmMTdiYTFiIiwiaWF0IjoxNjE3MTQ4MDY3LCJleHAiOjE2MTk3NDAwNjd9.SZXylt-4G9KtS1Tr52ei75l0Y2eYqYWhVYzQLzXMvS8"

# tokens.idTokenName

Returns the name of the cookie that holds the JWT ID token.

import Userfront from "@userfront/core";
Userfront.init("demo1234");

Userfront.tokens.idTokenName;

// => "id.demo1234"
Last Updated: 6/22/2022, 12:10:49 AM