CorvidReference

wix-users-backend

The wix-users-backend module contains functionality for working with your site's users from backend 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-backend module:

   import wixUsers from 'wix-users-backend';

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.

Table of Contents

PROPERTIES

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

FUNCTIONS

?
Perform actions on an object.
approveByEmail( )Approve a member whose status is "Pending" using an email address.
approveByToken( )Approve a member whose status is "Pending" using an approval token.
blockByEmail( )Blocks a member from logging into the site.
emailUser( )Sends a Triggered Email to the specified site member.
generateSessionToken( )Create a session token for a member authenticated by a 3rd party.
login( )Logs a user in based on email and password.
register( )Registers a new site member.

OBJECTS

?
Objects used when setting, getting, or calling the properties and methods listed above.
RegistrationResultAn object that contains information about the results of a site registration.

Related Content

FAQ

    When should I write code in the backend instead of the client side?
    How can I get the current user's name?
    How do I use a 3rd-party application to authenticate my users?

currentUser

Gets the current user viewing the site.

Description

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

Syntax

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

Examples

Get the current user's information

import wixUsers from 'wix-users-backend';

// ...

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"
  } );

approveByEmail( )

Approve a member whose status is "Pending" using an email address.

Description

The approveByEmail() function returns a Promise that resolves to a session token when the specified user is approved.

A member's status is "Pending" after you've called the register() function when the site's membership policy is set to manual approval. To learn more about setting you site's membership approval policy, see Editing Your Member Signup Settings.

Pass the member's email address in the email parameter.

Syntax

function approveByEmail(email: string): Promise<string>
PARAMETERS
?
Values that you pass to a function.
email
string
Email address of the user to approve.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<string>

Fulfilled - A session token for logging in the approved user in client-side code. Rejected - Error message.

Examples

Approve a pending member using an email address

This example contains a backend function which approves a pending user using an email address and returns a session token to be used in client-side code to log in the user who was just approved.

import wixUsers from 'wix-users-backend';

export function myBackendFunction(email) {
  return wixUsers.approveByEmail(email)
    .then( (sessionToken) => {
      return {sessionToken, "approved": true};
    } );
    .catch( (error) => {
      return {"approved": false, "reason": error};
    } );
  }
}

approveByToken( )

Approve a member whose status is "Pending" using an approval token.

Description

The approveByToken() function returns a Promise that resolves to a session token when the specified user is approved.

A member's status is "Pending" after you've called the register() function when the site's membership policy is set to manual approval. To learn more about setting you site's membership approval policy, see Editing Your Member Signup Settings.

Use the approvalToken parameter of the RegistrationResult object returned from the register() function when calling approveByToken.

Syntax

function approveByToken(token: string): Promise<string>
PARAMETERS
?
Values that you pass to a function.
token
string
Approval token returned by the register() function.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<string>

Fulfilled - A session token for logging in the approved user in client-side code. Rejected - Error message.

Examples

Approve a pending member using an approval token

This example contains a backend function which approves a pending user using an approval token and returns a session token to be used in client-side code to log in the user who was just approved.

import wixUsers from 'wix-users-backend';

export function myBackendFunction(token) {
  return wixUsers.approveByToken(token)
    .then( (sessionToken) => {
      return {sessionToken, "approved": true};
    } );
    .catch( (error) => {
      return {"approved": false, "reason": error};
    } );
  }
}

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 will be approved or not. If approved, the register() function is called, the registration is approved programmatically using the approveByToken() function, 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.

The code is split between three locations:

  • A backend web module named register.jsw.
  • The page code for the page where users register.
  • The page code for the page where users confirm their registration.
/*******************************
 * backend code - register.jsw *
 *******************************/
import wixUsers from 'wix-users-backend';

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
    wixUsers.emailUser('verifyRegistration', results.user.id, {
      "variables": {
        "name": firstName,
        "verifyLink": `http://yourdomain.com/post-register?token=${results.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';

export function button_click(event) {
  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 wixUsers from 'wix-users';
import {doApproval} from 'backend/register';

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

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

blockByEmail( )

Blocks a member from logging into the site.

Description

The blockByEmail() function returns a Promise that resolves when the specified user has been blocked.

Pass the member's email address in the email parameter.

Syntax

function blockByEmail(email: string): Promise<void>
PARAMETERS
?
Values that you pass to a function.
email
string
Email address of the user to approve.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>

Fulfilled - When specified member is blocked. Rejected - Error message.

Examples

Block a member using an email address

import wixUsers from 'wix-users-backend';

export function myBackendFunction(email) {
  wixUsers.blockByEmail(email)
    .then( () => {
      // user has been blocked
    } );
  }
}

emailUser( )

Sends a Triggered Email to the specified 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.

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.

Syntax

function emailUser(emailId: string, toUser: string, [options: TriggeredEmailOptions]): Promise<void>
PARAMETERS
?
Values that you pass to a function.
emailId
string
The Email ID of the Triggered Email to send.
toUser
string
The User ID of the email recipient.
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 a site member

import wixUsers from 'wix-users-backend';

export function myBackendFunction() {
  let userId = // get user ID

  wixUsers.emailUser("emailID", userId)
    .then( () => {
      // email has been sent
    } )
    .catch( (err) => {
      // there was an error sending the email
  } );
}

Send a Triggered Email to a site member with variable values

import wixUsers from 'wix-users-backend';

export function myBackendFunction() {
  let userId = // get user ID
  let value1 = // value for variable1

  wixUsers.emailUser("emailID", userId, {
      "variables": {
        "variable1": value1,
        "variable2": "value for variable2"
      }
    } )
    .then( () => {
      // email has been sent
    } )
    .catch( (err) => {
      // there was an error sending the email
    } );
}

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.

The code is split between three locations:

  • A backend web module named register.jsw.
  • The page code for the page where users register.
  • The page code for the page where users confirm their registration.
/*******************************
 * backend code - register.jsw *
 *******************************/
import wixUsers from 'wix-users-backend';

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
    wixUsers.emailUser('verifyRegistration', results.user.id, {
      "variables": {
        "name": firstName,
        "verifyLink": `http://yourdomain.com/post-register?token=${results.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';

export function button_click(event) {
  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 wixUsers from 'wix-users';
import {doApproval} from 'backend/register';

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

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

generateSessionToken( )

Create a session token for a member authenticated by a 3rd party.

Description

The generateSessionToken() function returns a Promise that resolves to a session token used to log a user into your site.

Use generateSessionToken() to bypass Wix member authentication when using a 3rd party service to authenticate your users. Meaning, you can provide Single Sign-On (SSO) for users where they are authenticated by a non-Wix entity to login to your Wix site.

If the specified email address corresponds to an existing member, a session token for logging in that member is generated.

If there is no existing member with the specified email address, a new member is created and a session token for logging in that member is generated. The member is created with a random password.

Syntax

function generateSessionToken(email: string): Promise<string>
PARAMETERS
?
Values that you pass to a function.
email
string
Email address of the user to approve.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<string>

Fulfilled - A session token for logging in the approved user in client-side code. Rejected - Error message.

Examples

Log a user in after 3rd party authentication

This example contains a backend function which uses a 3rd party authentication service to authenticate a user. If the authentication is successful, a session session token is returned to the client-side and used to log in the authenticated user.

/*******************************
 * backend code - login.jsw *
 *******************************/
import wixUsers from 'wix-users-backend';
import {authBy3rdParty} from 'backend/authentications';

export function getLoginToken(email, password) {
  // authenticate using 3rd party
  return authBy3rdParty(email, password)
    .then( (isAuthenticated) => {
      // if authenticated generate and return session token
      if(isAuthenticated){
        return wixUsers.generateSessionToken(email)
          .then( (sessionToken) => {
            return {"sessionToken": sessionToken, "approved": true};
          } );
      }
      // if not authenticated return non-approval
      return {"approved": false};
    } );
}

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

export async function button_onClick(event) {
  // call backend function
  getLoginToken($w("#email").value, $w("#password").value)
    .then( (loginResult) => {
      // if approved log the user in with the session token
      if (loginResult.approved) {
        wixUsers.applySessionToken(loginResult.sessionToken);
      }
      // if not approved log a message
      else {
        console.log("User not approved.");
      }
    } );
}

login( )

Logs a user in based on email and password.

Description

The login() function returns a Promise that resolves to a session token used to log a user into your site.

The returned sessionToken must be applied using the applySessionToken() function in client-side code to complete the login.

Syntax

function login(email: string, password: string): Promise<string>
PARAMETERS
?
Values that you pass to a function.
email
string
The email address to use when logging the user in.
password
string
The password to use when logging the user in.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<string>

Fulfilled - Session token for logging the user in. Rejected - Error message.

Examples

Log in a user

This example contains a backend function which returns a session token to be used in client-side code to log in the user with the given email and password.

import wixUsers from 'wix-users-backend';

export function myBackendFunction(email, password) {
  return wixUsers.login(email, password)
    .then( (sessionToken) => {
      return {sessionToken, "approved": true};
    } )
    .catch( (error) => {
      return {"approved": false, "reason": error};
    } );
}

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.

The specified password must be between 4 and 15 characters.

If Site Members is configured for automatic approval, the register() function returns a status of "Active" and the user will be 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 will be 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.

The sessionToken returned when the new member is "Active" must be applied using the applySessionToken() function in client-side code to complete the user registration by logging in the registered user.

Note

When member registration is set to auto approve, calling the client-side register() function 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
?
Values that you pass to a function.
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 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 will be 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.

The code is split between three locations:

  • A backend web module named register.jsw.
  • The page code for the page where users register.
  • The page code for the page where users confirm their registration.
/*******************************
 * backend code - register.jsw *
 *******************************/
import wixUsers from 'wix-users-backend';

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
    wixUsers.emailUser('verifyRegistration', results.user.id, {
      "variables": {
        "name": firstName,
        "verifyLink": `http://yourdomain.com/post-register?token=${results.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';

export function button_click(event) {
  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 wixUsers from 'wix-users';
import {doApproval} from 'backend/register';

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

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

RegistrationResult

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

Syntax

type RegistrationResult = {
  status: string
  sessionToken: string
  approvalToken: string
  user: User
}
MEMBERS
?
The properties of an object.
status
string
Registration status. Either "Pending" or "Active".
sessionToken(Optional)
string

A token used to log in the current user as a site member. Pass the token from your backend code to client-side code and use it when calling the applySessionToken() function. The token is only available when status is "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.