Handle Visitors Using the JavaScript SDK

Note: This article is only relevant for self-managed headless projects. For Wix-managed headless projects, the CLI automatically generates and manages visitor tokens for you.

Use visitor tokens to maintain anonymous visitor sessions in your self-managed headless project. The SDK uses these tokens when making requests to Wix APIs on behalf of a visitor, preserving their data such as cart items or event reservations.

Step 1 | Create a client

Create a Wix client with the OAuth strategy. When initializing your app, check if you have stored tokens from a previous session. If tokens exist, pass them to the client to resume the session. If not, create a new client without tokens.

Copy

Note: OAuth for Wix Headless only requires a client ID. It doesn't require a client secret.

If no tokens are passed, tokens are prepared but not yet populated. They're created when you either:

If tokens are passed, the client resumes the previous visitor's session, preserving their data such as cart items or event reservations.

Step 2 | Make API calls

Make API calls as usual. The client handles token generation and renewal automatically.

Copy

After your first API call, the client has valid tokens containing:

  • An access token that expires after 4 hours.
  • A refresh token for generating new access tokens.

Step 3 | Save tokens to persist the session

To maintain a visitor's session across page reloads or app restarts, save the tokens to local storage, a cookie, or a file.

Retrieve the current tokens using getTokens():

Copy

The function returns an object in this format:

Copy

Save the tokens to your preferred storage:

Copy

Manage tokens manually

In most cases, the client manages tokens automatically. Use these methods when you need manual control.

Set tokens on an existing client

If you already have a client instance and need to set tokens on it later, use setTokens():

Copy

Once tokens are set, the visitor's data is preserved. For example, items added to a cart or tickets reserved are reflected in future API calls.

Generate tokens explicitly

Call generateVisitorTokens() to create tokens before making any API calls:

Copy

Confirm or renew existing tokens

Pass existing tokens to generateVisitorTokens() to confirm they're valid or renew them if expired:

Copy

The function returns:

  • The same tokens if the access token is still valid.
  • A new access token if the access token expired but the refresh token is valid.
  • New access and refresh tokens if the refresh token is invalid.

Force token renewal

Use renewToken() to generate a new access token without checking if the current one is valid:

Copy

Check login status

Use loggedIn() to check if the current visitor is a logged-in member:

Copy

Example

This example demonstrates creating a client that handles both new and returning visitors, making API calls, and saving tokens:

Copy

See also

Did this help?