CodeAPI

wix-users

The wix-users module contains functionality for working with your site's users from client-side code.

There are three types of users:

  • Visitor - A user who is not logged into your site.
  • Member - A user who is logged into your site.
  • Admin - The owner of the site.

To use the Users API, import wixUsers from the wix-users module:

   import wixUsers from 'wix-users';

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

The APIs in wix-users can only be used once the page has loaded. Therefore, you must use them in code that is contained in or is called from the onReady() event handler or any element event handler.

Table of Contents

PROPERTIES

?
Store values associated with an object.
currentUserGets the current user viewing the site.

FUNCTIONS

?
Perform actions on an object.
applySessionToken( )Logs the current user into the site using the given session token.
emailUser( )Sends a Triggered Email to the currently logged-in site member.
login( )Logs a user in based on email and password.
logout( )Logs the current user out of the site.
onLogin( )Sets the function that runs when a user logs in.
promptForgotPassword( )Prompts the current site visitor with a password reset.
promptLogin( )Prompts the current site visitor to log in as a site member.
register( )Registers a new site member.

OBJECTS

?
Objects used when setting, getting, or calling the properties and methods listed above.
LoginOptionsAn object used by the promptLogin() function to determine how the login dialog box appears.
RegistrationOptionsAn object that contains information about a site registration.
RegistrationResultAn object that contains information about the results of a site registration.
TriggeredEmailOptionsAn object used when sending a Triggered Email.

currentUser

Gets the current user viewing the site.

Description

Gets a User object containing information about the user currently viewing the site.

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

The APIs in wix-users can only be used once the page has loaded. Therefore, you must use them in code that is contained in or is called from the onReady() event handler or any element event handler.

Syntax

get currentUser(): User
TYPE
?
The kind of data the property stores.

Examples

Get the current user's information

import wixUsers from 'wix-users';

// ...

let user = wixUsers.currentUser;

let userId = user.id;           // "r5cme-6fem-485j-djre-4844c49"
let isLoggedIn = user.loggedIn; // true

user.getEmail()
  .then( (email) => {
    let userEmail = email;      // "user@something.com"
  } );

user.getRoles()
  .then( (roles) => {
    let firstRole = roles[0];
    let roleName = firstRole.name;                // "Role Name"
    let roleDescription = firstRole.description;  // "Role Description"
  } );

user.getPricingPlans()
  .then( (pricingPlans) => {
    let firstPlan = pricingPlans[0];
    let planName = firstPlan.name;          // "Gold"
    let startDate = firstPlan.startDate;    // Wed Aug 29 2018 09:39:41 GMT-0500 (Eastern Standard Time)
    let expiryDate = firstPlan.expiryDate;  // Thu Nov 29 2018 08:39:41 GMT-0400 (Eastern Daylight Time)
  } );

applySessionToken( )

Logs the current user into the site using the given session token.

Description

The applySessionToken() function returns a Promise that resolves when the given session token is applied and the current user is logged into the site.

You receive a session token from the following functions called from backend code:

Pass the returned session token to your client-side code and apply it by calling applySessionToken() to complete the process started by one of the above functions.

Syntax

function applySessionToken(sessionToken: string): Promise<void>
PARAMETERS
?
The kind of data the property stores.
sessionToken
string
The session token to apply.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>
Fulfilled - When the token as been applied.

Examples

Log in the current user by applying a session token

import wixUsers from 'wix-users';

// ...

wixUsers.applySessionToken(sessionToken)
  .then( () => {
    console.log("User logged in.");
  } );

Register a user using a 3rd party for approval

This example demonstrates a common 3rd party approval flow. The backend code calls a 3rd party function that determines whether the user is approved or not. If approved, the register() function is called, the registration is approved programmatically, and a session token is returned to the calling client-side code. If rejected, the blockByEmail() function is called.

/*******************************
 * backend code - register.jsw *
 *******************************/
import wixUsers from 'wix-users-backend';
import {approveBy3rdParty} from 'some-backend-module';

export function doRegistration(email, password, firstName, lastName) {
  // call a 3rd party API to check if the user is approved
  return approveBy3rdParty(email, password)
    .then( (isApproved) => {
      // if approved by 3rd party
      if (isApproved) {
        // register the user
        return wixUsers.register(email, password, {
          "contactInfo": {
            "firstName": firstName,
            "lastName": lastName
          }
        } )
        // user is now registered and pending approval
        // approve the user
          .then( (result) => wixUsers.approveByToken(result.approvalToken) )
          // user is now active, but not logged in
          // return the session token to log in the user client-side
          .then( (sessionToken) => {
            return {sessionToken, "approved": true};
          } );
      }
      // if not approved by 3rd party
      else {
        return {"approved": false};
      }
    } )
}

/********************
 * client-side code *
 ********************/
import wixUsers from 'wix-users';
import {doRegistration} from 'backend/register';

// ...

let email = // the user's email addresses
let password = // the user's password
let firstName = // the user's first name
let lastName = // the user's last name

doRegistration(email, password, firstName, lastName)
  .then( (result) => {
    if (result.approved)
    // log the user in
      wixUsers.applySessionToken(result.sessionToken);
    else {
      console.log("Not approved!");
    }
  } );

Register a user sending an email for confirmation

This example demonstrates a common email verification flow. A user is initially registered but not yet approved. At registration, a verification email is sent with a link to a verification page. When a user goes to the verification page, the approval is granted and the user is logged into the site.

/*******************************
 * backend code - register.jsw *
 *******************************/
import wixUsers from 'wix-users-backend';
import {sendEmailUsing3rdParty} from 'some-backend-module';

export function doRegistration(email, password, firstName, lastName) {
  // register the user
  return wixUsers.register(email, password, {
    "contactInfo": {
      "firstName": firstName,
      "lastName": lastName
    }
  } )
    .then( (results) => {
      // user is now registered and pending approval
      // send a registration verification email
      return sendEmailUsing3rdParty('verify-registration', email,{
        "name": firstName,
        "verifyLink": `http://domain.com/post-register?token=${approvalToken}`
      } );
    } );
}

export function doApproval(token) {
  // approve the user
  return wixUsers.approveByToken(token)
  // user is now active, but not logged in
  // return the session token to log in the user client-side
    .then( (sessionToken) => {
      return {sessionToken, "approved": true};
    } )
    .catch( (error) => {
      return {"approved": false, "reason": error};
    } );
}

/*********************************
 * client-side registration code *
 *********************************/
import wixUsers from 'wix-users';
import {doRegistration} from 'backend/register';

// ...

let email = // the user's email address
let password = // the user's password
let firstName = // the user's first name
let lastName = // the user's last name

doRegistration(email, password, firstName, lastName)
  .then( () => {
    console.log("Confirmation email sent.");
  } );

/**************************************
 * client-side post-registration code *
 **************************************/
import wixLocation from 'wix-location';
import {doApproval} from 'backend/register';

$w.onReady( () => {
  // get the token from the URL
  let token = wixLocation.query.token;

  doAppoval(token)
    .then( (result) => {
      if (result.approved)
        // log the user in
        wixUsers.applySessionToken(result.sessionToken);
      else
        console.log("Not approved!");
    } );
}

emailUser( )

Sends a Triggered Email to the currently logged-in site member.

Description

To learn more about Triggered Emails, see:

Before using the emailUser() function, you need to set up at least one Triggered Email.

Specify which email to send by passing the email's ID in the emailId parameter.

Specify which member the email is sent to by passing the member's user ID in the toUser parameter. You can only send the email to the currently logged-in member. You can get that member's ID using the id property of the currentUser.

If the specified Triggered Email contains variables, you can pass values for those variables using the optional options parameter. You pass a TriggeredEmailOptions object which contains the values to be inserted into your email in place of the variables defined in that email. The values passed must be strings. If the object you pass to the options parameter does not contain a key:value pair for a variable in your Triggered Email, the fallback value defined when creating your Triggered Email is inserted in place of the variable.

Note that Triggered Emails generates a code snippet for each of your email templates. The generated code includes the email's ID and keys for all the email's variable names. You can copy and paste the snippet into your code. Then, you need to define values for the toUser property and for each variable key. To learn how to use the generated snippet in your code, see How to Send a Triggered Email with Code.

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

Syntax

function emailUser(emailId: string, toUser: string, [options: TriggeredEmailOptions]): Promise<void>
PARAMETERS
?
The kind of data the property stores.
emailId
string
The Email ID of the Triggered Email to send.
toUser
string
The User ID of the currently signed-in member.
options(Optional)
Variable values to insert into the email.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>

Fulfilled - When the email is sent. Rejected - Error message.

Examples

Send a Triggered Email to the currently logged-in member

import wixUsers from 'wix-users';

// ...

let userId = wixUsers.currentUser.id;

wixUsers.emailUser("emailID", userId)
  .then( () => {
    console.log("Triggered email sent");
  } )
  .catch( (err) => {
    console.log(err);
  } );

Send a Triggered Email to the currently logged-in member with variable values

import wixUsers from 'wix-users';

// ...

let userId = wixUsers.currentUser.id;
let value1 = // value for variable1

wixUsers.emailUser("emailID", userId, {
    "variables": {
      "variable1": value1,
      "variable2": "value for variable2"
    }
  } )
  .then( () => {
    console.log("Triggered email sent");
  } )
  .catch( (err) => {
    console.log(err);
  } );

login( )

Logs a user in based on email and password.

Description

The login() function returns a Promise that resolves when the user with the specified email address and password is logged in.

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

Syntax

function login(email: string, password: string): Promise<void>
PARAMETERS
?
The kind of data the property stores.
email
string
The email address to use when logging the user.
password
string
The password to use when logging the user.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>

Fulfilled - When the user has been logged in. Rejected - Error message.

Examples

Logs a user in

import wixUsers from 'wix-users';

let email = // email address of user to log in
let password = // password of user to log in

wixUsers.login(email, password)
  .then( () => {
    console.log("User is logged in");
  } )
  .catch( (err) => {
    console.log(err);
  } );

Logs a user in using data from input elements

import wixUsers from 'wix-users';

let email = $w("#email");
let password = $w("#password");

wixUsers.login(email, password)
  .then( () => {
    console.log("User is logged in");
  } )
  .catch( (err) => {
    console.log(err);
  } );

logout( )

Logs the current user out of the site.

Description

The logout() function logs the current user out of the site.

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

The APIs in wix-users can only be used once the page has loaded. Therefore, you must use them in code that is contained in or is called from the onReady() event handler or any element event handler.

Syntax

function logout(): void

Examples

Log out the current user

import wixUsers from 'wix-users';

// ...

wixUsers.logout();

onLogin( )

Sets the function that runs when a user logs in.

Description

Use the onLogin() function for code you want to run after a user successfully logs into your site.

Usually, you want to call the onLogin() function in the Site tab of the code panel so that the onLogin() event handler runs no matter which page on your site a user uses to log in.

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

The APIs in wix-users can only be used once the page has loaded. Therefore, you must use them in code that is contained in or is called from the onReady() event handler or any element event handler.

Syntax

function onLogin(handler: LoginHandler): void
PARAMETERS
?
The kind of data the property stores.
handler
The name of the function or the function expression to run when a user has logged in.

Examples

Run code when a user logs in

import wixUsers from 'wix-users';

// ...

wixUsers.onLogin( (user) => {
  let userId = user.id;           // "r5cme-6fem-485j-djre-4844c49"
  let isLoggedIn = user.loggedIn; // true
  let userRole = user.role;       // "Member"
} );

promptForgotPassword( )

Prompts the current site visitor with a password reset.

Description

The promptForgotPassword() function returns a Promise that resolves when the user has sumbitted the forgot password form.

The promptForgotPassword() function cannot be called before the page is ready.

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

The APIs in wix-users can only be used once the page has loaded. Therefore, you must use them in code that is contained in or is called from the onReady() event handler or any element event handler.

See Also

promptLogin( )

Syntax

function promptForgotPassword([language: string]): Promise<void>
PARAMETERS
?
The kind of data the property stores.
language(Optional)
string
The language of the reset password form. Defaults to "English" if not passed or the given language is not one of the languages found in the Permissions tab of the Page Settings panel in the Editor.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>
Rejected - Message that the dialog was canceled, user is already logged in, or any other reason the password reset failed.

Examples

Prompt the user with a password reset

import wixUsers from 'wix-users';

// ...

wixUsers.promptForgotPassword();

Prompt the current user to login with given language

import wixUsers from 'wix-users';

// ...

wixUsers.promptForgotPassword()
  .then( ( ) => {
    console.log("Password reset submitted");
  } )
  .catch( (err) => {
    let errorMsg = err; // "The user closed the forgot password dialog"
  } );

promptLogin( )

Prompts the current site visitor to log in as a site member.

Description

The promptLogin() function returns a Promise that resolves to the newly logged in user when the login has completed.

The promptLogin() function cannot be called before the page is ready.

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

The APIs in wix-users can only be used once the page has loaded. Therefore, you must use them in code that is contained in or is called from the onReady() event handler or any element event handler.

See Also

promptForgotPassword( )

Syntax

function promptLogin(options: LoginOptions): Promise<User>
PARAMETERS
?
The kind of data the property stores.
options
The options that determine how the login dialog box appears.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<User>

Fulfilled - Information about the newly logged in user. Rejected - Message that the dialog was canceled, or any other reason the user failed to log in.

Examples

Prompt the current user to login

import wixUsers from 'wix-users';

// ...

wixUsers.promptLogin()
  .then( (user) => {
    let userId = user.id;           // "r5me-6fem-45jf-djhe-484349"
    let isLoggedIn = user.loggedIn; // true
    let userRole = user.role;       // "member"
    return user.getEmail();
  } )
  .then( (email) => {
    let userEmail = email;          // "user@something.com"
  } )
  .catch( (err) => {
    let errorMsg = err;          // "The user closed the login dialog"
  } );

Prompt the current user to login with given options

import wixUsers from 'wix-users';

// ...

let options = {"mode": "login", "lang": "es"};

wixUsers.promptLogin(options)
  .then( (user) => {
    let userId = user.id;           // "r5me-6fem-45jf-djhe-484349"
    let isLoggedIn = user.loggedIn; // true
    let userRole = user.role;       // "member"
    return user.getEmail();
  } )
  .then( (email) => {
    let userEmail = email;          // "user@something.com"
  } )
  .catch( (err) => {
    let errorMsg = err;             // "The user closed the login dialog"
  } );

register( )

Registers a new site member.

Description

The register() function returns a Promise that resolves to a RegistrationResult object when the user is either registered or is pending registration.

If Site Members is configured for automatic approval, the register() function returns a status of "Active" and the user becomes an active member of the site.

If Site Members is configured for manual approval, the register() function returns a status of "Pending" and the user becomes a pending member of the site. In order to activate a pending user, the site owner can approve the user manually, using the Contacts application or you can call the approveByToken() or approveByEmail() functions.

Note

The APIs in wix-users are only partially functional when previewing your site. View a published version of your site to see their complete functionality.

When member registration is set to auto approve, calling the register() function client-side is equally as secure as calling it from backend code. However, when member approval is set to manual, calling the backend version of the register() function allows you to construct more secure approval flows.

Syntax

function register(email: string, password: string, [options: RegistrationOptions]): Promise<RegistrationResult>
PARAMETERS
?
The kind of data the property stores.
email
string
The email address to use when registering the user as a site member.
password
string
The password the newly added site member will use to log in.
options(Optional)
Registration options.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.

Fulfilled - When the user has been registered. Rejected - Error message.

Examples

Register a user as a site member with manual approval

import wixUsers from 'wix-users';

// ...

let email = // the user's email addresses
let password = // the user's password

wixUsers.register(email, password)
  .then( (result) => {
    let status = result.status; // "Pending"
    let approvalToken = result.approvalToken;
    let user = result.user;
  } );

Register a user as a site member with auto approval

import wixUsers from 'wix-users';

// ...

let email = // the user's email addresses
let password = // the user's password

wixUsers.register(email, password)
  .then( (result) => {
    let status = result.status; // "Active"
    let user = result.user;
  } );

Register a user as a site member with registration options

import wixUsers from 'wix-users';

// ...

let email = // the user's email addresses
let password = // the user's password
let firstName = // the user's first name
let lastName = // the user's last name
let phone =  // the user's phone number
let nickname = // the user's nickname

wixUsers.register(email, password, {
    contactInfo: {
        "firstName": firstName,
        "lastName": lastName,
        "phone": phone,
        "nickname": nickname
    }
  } )
  .then( (result) => {
    let resultStatus = result.status;
  } );

LoginOptions

An object used by the promptLogin() function to determine how the login dialog box appears.

See Also

promptLogin( )

Syntax

type LoginOptions = {
  mode: string
  lang: string
}
MEMBERS
?
The kind of data the property stores.
mode(Optional)
string
What type of login experience to present: "login" or "signup". Defaults to the option chosen in the Member Signup Settings panel in the Editor.
lang(Optional)
string
The two letter language code of the language to show the login form in. Defaults to "en" if the property doesn't exist or the given language is not one of the languages found in the Permissions tab of the Page Settings panel in the Editor.

Examples

Prompt the current user to login

import wixUsers from 'wix-users';

// ...

let options = {"mode": "login", "lang": "es"};

wixUsers.promptLogin(options)
  .then( (user) => {
    let userId = user.id;           // "r5me-6fem-45jf-djhe-484349"
    let isLoggedIn = user.loggedIn; // true
    let userRole = user.role;       // "member"
    return user.getEmail();
  } )
  .then( (email) => {
    let userEmail = email;          // "user@something.com"
  } )
  .catch( (err) => {
    let errorMsg = err;             // "The user closed the login dialog"
  } );

RegistrationOptions

An object that contains information about a site registration.

See Also

register

Syntax

type RegistrationOptions = {
  contactInfo: ContactInfo
}
MEMBERS
?
The kind of data the property stores.
contactInfo
Contact information.

RegistrationResult

An object that contains information about the results of a site registration.

See Also

register

Syntax

type RegistrationResult = {
  status: string
  approvalToken: string
  user: User
}
MEMBERS
?
The kind of data the property stores.
status
string
Registration status. Either "Pending" or "Active".
approvalToken(Optional)
string

A token for approving the user as a site member using the approveByToken() function. The token is safe to pass via email or from client-side code to backend code. The token is only available when status is "Pending".

user
The user that has been registered.

TriggeredEmailOptions

An object used when sending a Triggered Email.

See Also

emailUser( )

Syntax

type TriggeredEmailOptions = {
  variables: Object
}
MEMBERS
?
The kind of data the property stores.
variables
Object

An object with key:value pairs where each key is a variable in the email template created in Triggered Emails and its corresponding value is the value to insert into the template in place of variable. The values must be strings.

Examples

Send a Triggered Email to the currently logged-in member

import wixUsers from 'wix-users';

// ...

let userId = wixUsers.currentUser.id;
let value1 = // value for variable1

wixUsers.emailUser("emailID", userId, {
    "variables": {
      "variable1": value1,
      "variable2": "value for variable2"
    }
  } )
  .then( () => {
    console.log("Triggered email sent");
  } )
  .catch( (err) => {
    console.log(err);
  } );