Skip to main content

Token Refresh and Error Handling

credentials_error Error Description​

When using @cloudbase/js-sdk, the login state may become invalid due to the following reasons, triggering the credentials_error event:

  1. refresh_token Expired: The refresh_token has exceeded its validity period and cannot refresh the access_token, requiring the user to log in again
  2. Token Updated: The account has been logged in on another device, causing the current device's token to become invalid

Configuring Token Validity Period​

You can configure the Token validity period in CloudBase Console - Identity Authentication - Token Management:

  • access_token Validity Period: Recommended to set to 7200 seconds (2 hours)
  • refresh_token Validity Period: Recommended to set to 2592000 seconds (30 days)
Tip

Configuration changes will only take effect for newly logged-in users. The token validity period of already logged-in users will not change.

Handling credentials_error Event​

Basic Handling​

import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not provided
});

const auth = app.auth();

// Monitor login state changes and handle credentials_error
auth.onLoginStateChanged((params) => {
const { eventType, msg } = params?.data || {};

switch (eventType) {
case "credentials_error":
// Method 1: refresh_token expired, need to log in again
if (msg && msg.includes("refresh_token")) {
console.warn("Login has expired, please log in again");
// Redirect to login page or call login popup
auth.toDefaultLoginPage();
}

// Method 2: Logged in on another device, token updated
if (msg && msg.includes("token updated")) {
console.warn("Account logged in on another device, please verify again");
// Prompt user to log in again
auth.toDefaultLoginPage();
}
break;

case "sign_out":
// Handle logout logic
console.log("User has logged out");
break;

case "sign_in":
// Handle successful login logic
console.log("User has logged in");
break;
}
});

Handling in Mini Programs​

In WeChat Mini Programs, you can optimize user experience with UI prompts:

import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai",
});

const auth = app.auth();

auth.onLoginStateChanged((params) => {
const { eventType, msg } = params?.data || {};

if (eventType === "credentials_error") {
wx.showModal({
title: "Login Expired",
content: "Your login has expired, please log in again",
confirmText: "Log In Again",
success: (res) => {
if (res.confirm) {
// Redirect to login page
wx.navigateTo({
url: "/pages/login/login",
});
}
},
});
}
});

Using Publishable Key to Avoid Errors Before Login​

If you need to query data models before user login (such as displaying homepage article list), you can use Publishable Key + anonymous identity query to avoid credentials_error:

import cloudbases from "@cloudbase/js-sdk/app";
import { registerAuth } from "@cloudbase/js-sdk/auth";
import { registerModel } from "@cloudbase/js-sdk/model";

registerAuth(cloudbases);
registerModel(cloudbases);

const app = cloudbases.init({
env: "your-env-id",
accessKey: "<YOUR_PUBLISHABLE_KEY>", // Get from console
});

// Anonymous query before login
const models = app.models;
const articles = await models.article.list();

// Log in when authentication is required
await app.auth().signInAnonymously();

Getting Publishable Key:

  1. Visit CloudBase Console - API Key Management
  2. Create or copy Publishable Key
  3. Pass the accessKey parameter during initialization

Best Practices​

  1. Global Monitoring: Register the onLoginStateChanged listener when the application starts (e.g., in App.onLaunch)
  2. User Prompts: Use Modal or Toast to notify users that login has expired
  3. Automatic Redirect: Automatically redirect to login page after login expires
  4. Save State: Record the user's current page path and redirect back to the original page after login