This document covers the management API capabilities available in the JavaScript SDK, which correspond to the features available in the backend management UI.
Note: All management API operations require superuser authentication (🔐).
The Settings Service provides comprehensive management of application settings, matching the capabilities available in the backend management UI.
Manage application settings including meta information, trusted proxy, rate limits, and batch configuration.
const settings = await pb.settings.getApplicationSettings();
// Returns: { meta, trustedProxy, rateLimits, batch }Example:
const appSettings = await pb.settings.getApplicationSettings();
console.log(appSettings.meta.appName); // Application name
console.log(appSettings.rateLimits.rules); // Rate limit rulesawait pb.settings.updateApplicationSettings({
meta: {
appName: "My App",
appURL: "https://example.com",
hideControls: false
},
trustedProxy: {
headers: ["X-Forwarded-For"],
useLeftmostIP: true
},
rateLimits: {
enabled: true,
rules: [
{
label: "api/users",
duration: 3600,
maxRequests: 100
}
]
},
batch: {
enabled: true,
maxRequests: 100,
interval: 200
}
});Update Meta Settings:
await pb.settings.updateMeta({
appName: "My App",
appURL: "https://example.com",
senderName: "My App",
senderAddress: "noreply@example.com",
hideControls: false
});Update Trusted Proxy:
await pb.settings.updateTrustedProxy({
headers: ["X-Forwarded-For", "X-Real-IP"],
useLeftmostIP: true
});Update Rate Limits:
await pb.settings.updateRateLimits({
enabled: true,
rules: [
{
label: "api/users",
audience: "public",
duration: 3600,
maxRequests: 100
}
]
});Update Batch Configuration:
await pb.settings.updateBatch({
enabled: true,
maxRequests: 100,
timeout: 30,
maxBodySize: 10485760
});Manage SMTP email settings and sender information.
const mailSettings = await pb.settings.getMailSettings();
// Returns: { meta: { senderName, senderAddress }, smtp }Example:
const mail = await pb.settings.getMailSettings();
console.log(mail.meta.senderName); // Sender name
console.log(mail.smtp.host); // SMTP hostUpdate both sender info and SMTP configuration in one call:
await pb.settings.updateMailSettings({
senderName: "My App",
senderAddress: "noreply@example.com",
smtp: {
enabled: true,
host: "smtp.example.com",
port: 587,
username: "user@example.com",
password: "password",
authMethod: "PLAIN",
tls: true,
localName: "localhost"
}
});await pb.settings.updateSMTP({
enabled: true,
host: "smtp.example.com",
port: 587,
username: "user@example.com",
password: "password",
authMethod: "PLAIN",
tls: true,
localName: "localhost"
});Send a test email to verify SMTP configuration:
await pb.settings.testMail(
"test@example.com",
"verification", // template: verification, password-reset, email-change, otp, login-alert
"_superusers" // collection (optional, defaults to _superusers)
);Email Templates:
verification- Email verification templatepassword-reset- Password reset templateemail-change- Email change confirmation templateotp- One-time password templatelogin-alert- Login alert template
Manage S3 storage configuration for file storage.
const s3Config = await pb.settings.getStorageS3();
// Returns: { enabled, bucket, region, endpoint, accessKey, secret, forcePathStyle }await pb.settings.updateStorageS3({
enabled: true,
bucket: "my-bucket",
region: "us-east-1",
endpoint: "https://s3.amazonaws.com",
accessKey: "ACCESS_KEY",
secret: "SECRET_KEY",
forcePathStyle: false
});await pb.settings.testStorageS3();
// Returns: true if connection succeedsManage auto-backup scheduling and S3 storage for backups.
const backupSettings = await pb.settings.getBackupSettings();
// Returns: { cron, cronMaxKeep, s3 }Example:
const backups = await pb.settings.getBackupSettings();
console.log(backups.cron); // Cron expression (e.g., "0 0 * * *")
console.log(backups.cronMaxKeep); // Maximum backups to keepawait pb.settings.updateBackupSettings({
cron: "0 0 * * *", // Daily at midnight (empty string to disable)
cronMaxKeep: 10, // Keep maximum 10 backups
s3: {
enabled: true,
bucket: "backup-bucket",
region: "us-east-1",
endpoint: "https://s3.amazonaws.com",
accessKey: "ACCESS_KEY",
secret: "SECRET_KEY",
forcePathStyle: false
}
});// Enable daily backups at midnight, keep 10 backups
await pb.settings.setAutoBackupSchedule("0 0 * * *", 10);
// Disable auto-backup
await pb.settings.disableAutoBackup();Common Cron Expressions:
"0 0 * * *"- Daily at midnight"0 0 * * 0"- Weekly on Sunday at midnight"0 0 1 * *"- Monthly on the 1st at midnight"0 0 * * 1,3"- Twice weekly (Monday and Wednesday)
await pb.settings.testBackupsS3();
// Returns: true if connection succeedsManage log retention and logging settings.
const logSettings = await pb.settings.getLogSettings();
// Returns: { maxDays, minLevel, logIP, logAuthId }await pb.settings.updateLogSettings({
maxDays: 30, // Retain logs for 30 days
minLevel: 0, // Minimum log level (negative=debug/info, 0=warning, positive=error)
logIP: true, // Log IP addresses
logAuthId: true // Log authentication IDs
});// Set log retention days
await pb.settings.setLogRetentionDays(30);
// Set minimum log level
await pb.settings.setMinLogLevel(0); // -100 to 100
// Enable/disable IP logging
await pb.settings.setLogIPAddresses(true);
// Enable/disable auth ID logging
await pb.settings.setLogAuthIds(true);Log Levels:
- Negative values: Debug/Info levels
0: Default/Warning level- Positive values: Error levels
Manage application backups - create, list, upload, delete, and restore backups.
const backups = await pb.backups.getFullList();
// Returns: Array<{ key, size, modified }>Example:
const backups = await pb.backups.getFullList();
backups.forEach(backup => {
console.log(`${backup.key}: ${backup.size} bytes, modified: ${backup.modified}`);
});await pb.backups.create("backup-2024-01-01");
// Creates a new backup with the specified basenameUpload an existing backup file:
const file = new File([backupData], "backup.zip", { type: "application/zip" });
await pb.backups.upload({ file });Or using FormData:
const formData = new FormData();
formData.append("file", fileBlob);
await pb.backups.upload(formData);await pb.backups.delete("backup-2024-01-01");
// Deletes the specified backup fileawait pb.backups.restore("backup-2024-01-01");
// Restores the application from the specified backup// First, get a file token
const token = await pb.files.getToken();
// Then build the download URL
const url = pb.backups.getDownloadURL(token, "backup-2024-01-01");
console.log(url); // Full URL to download the backupQuery and analyze application logs.
const result = await pb.logs.getList(1, 30, {
filter: 'level >= 0',
sort: '-created'
});
// Returns: { page, perPage, totalItems, totalPages, items }Example with filtering:
// Get error logs from the last 24 hours
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const errorLogs = await pb.logs.getList(1, 50, {
filter: `level > 0 && created >= "${yesterday.toISOString()}"`,
sort: '-created'
});
errorLogs.items.forEach(log => {
console.log(`[${log.level}] ${log.message}`);
});const log = await pb.logs.getOne("log-id");
// Returns: LogModel with full log detailsconst stats = await pb.logs.getStats({
filter: 'level >= 0' // Optional filter
});
// Returns: Array<{ total, date }> - hourly statisticsExample:
const stats = await pb.logs.getStats();
stats.forEach(stat => {
console.log(`${stat.date}: ${stat.total} requests`);
});Manage and execute cron jobs.
const cronJobs = await pb.crons.getFullList();
// Returns: Array<{ id, expression }>Example:
const cronJobs = await pb.crons.getFullList();
cronJobs.forEach(job => {
console.log(`Job ${job.id}: ${job.expression}`);
});Manually trigger a cron job:
await pb.crons.run("job-id");
// Executes the specified cron job immediatelyExample:
const cronJobs = await pb.crons.getFullList();
const backupJob = cronJobs.find(job => job.id.includes("backup"));
if (backupJob) {
await pb.crons.run(backupJob.id);
console.log("Backup job executed manually");
}Check the health status of the API.
const health = await pb.health.check();
// Returns: Health status informationExample:
try {
const health = await pb.health.check();
console.log("API is healthy:", health);
} catch (error) {
console.error("Health check failed:", error);
}Manage collections (schemas) programmatically.
const collections = await pb.collections.getList(1, 30);
// Returns: Paginated list of collectionsconst collection = await pb.collections.getOne("collection-id-or-name");
// Returns: Full collection schemaconst collection = await pb.collections.create({
name: "posts",
type: "base",
schema: [
{
name: "title",
type: "text",
required: true
},
{
name: "content",
type: "editor",
required: false
}
]
});await pb.collections.update("collection-id", {
schema: [
// Updated schema
]
});await pb.collections.delete("collection-id");Delete all records in a collection (keeps the schema):
await pb.collections.truncate("collection-id");const collections = [
{
name: "collection1",
// ... collection schema
},
{
name: "collection2",
// ... collection schema
}
];
await pb.collections.import(collections, false); // false = don't delete missing collectionsimport BosBase from 'bosbase';
const pb = new BosBase('http://127.0.0.1:8090');
// Authenticate as superuser
await pb.collection('_superusers').authWithPassword('admin@example.com', 'password');
// Check current backup settings
const backupSettings = await pb.settings.getBackupSettings();
console.log("Current backup schedule:", backupSettings.cron);
// List all existing backups
const backups = await pb.backups.getFullList();
console.log(`Found ${backups.length} backups`);
// Create a new backup
await pb.backups.create(`manual-backup-${new Date().toISOString().split('T')[0]}`);
console.log("Backup created successfully");
// Get updated backup list
const updatedBackups = await pb.backups.getFullList();
console.log(`Now have ${updatedBackups.length} backups`);
// Configure auto-backup (daily at 2 AM, keep 7 backups)
await pb.settings.setAutoBackupSchedule("0 2 * * *", 7);
console.log("Auto-backup configured");
// Test backup S3 connection if configured
try {
await pb.settings.testBackupsS3();
console.log("S3 backup storage is working");
} catch (error) {
console.warn("S3 backup storage test failed:", error);
}import BosBase from 'bosbase';
const pb = new BosBase('http://127.0.0.1:8090');
// Authenticate as superuser
await pb.collection('_superusers').authWithPassword('admin@example.com', 'password');
// Get log settings
const logSettings = await pb.settings.getLogSettings();
console.log("Log retention:", logSettings.maxDays, "days");
console.log("Minimum log level:", logSettings.minLevel);
// Get recent error logs
const errorLogs = await pb.logs.getList(1, 20, {
filter: 'level > 0',
sort: '-created'
});
console.log(`Found ${errorLogs.totalItems} error logs`);
errorLogs.items.forEach(log => {
console.log(`[${log.level}] ${log.message} - ${log.created}`);
});
// Get hourly statistics for the last 24 hours
const stats = await pb.logs.getStats({
filter: 'created >= "' + new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString() + '"'
});
console.log("Hourly request statistics:");
stats.forEach(stat => {
console.log(`${stat.date}: ${stat.total} requests`);
});
// Update log settings to retain logs for 14 days
await pb.settings.setLogRetentionDays(14);
console.log("Log retention updated to 14 days");import BosBase from 'bosbase';
const pb = new BosBase('http://127.0.0.1:8090');
// Authenticate as superuser
await pb.collection('_superusers').authWithPassword('admin@example.com', 'password');
// Get current application settings
const appSettings = await pb.settings.getApplicationSettings();
console.log("App Name:", appSettings.meta?.appName);
console.log("App URL:", appSettings.meta?.appURL);
// Update application configuration
await pb.settings.updateApplicationSettings({
meta: {
appName: "My Production App",
appURL: "https://api.example.com",
hideControls: false
},
rateLimits: {
enabled: true,
rules: [
{
label: "api/users",
duration: 3600,
maxRequests: 100
},
{
label: "api/posts",
duration: 3600,
maxRequests: 200
}
]
},
batch: {
enabled: true,
maxRequests: 100,
interval: 200
}
});
console.log("Application settings updated");
// Configure trusted proxy
await pb.settings.updateTrustedProxy({
headers: ["X-Forwarded-For", "X-Real-IP"],
useLeftmostIP: true
});
console.log("Trusted proxy configured");All management API methods can throw ClientResponseError. Always handle errors appropriately:
try {
await pb.backups.create("my-backup");
console.log("Backup created successfully");
} catch (error) {
if (error.status === 401) {
console.error("Authentication required");
} else if (error.status === 403) {
console.error("Superuser access required");
} else {
console.error("Error:", error.message);
}
}-
Authentication: All management API operations require superuser authentication. Use
pb.collection('_superusers').authWithPassword()to authenticate. -
Rate Limiting: Be mindful of rate limits when making multiple management API calls.
-
Backup Safety: Always test backup restoration in a safe environment before using in production.
-
Log Retention: Setting appropriate log retention helps manage storage usage.
-
Cron Jobs: Manual cron execution is useful for testing but should be used carefully in production.
For more information on specific services, see:
- Settings API - Detailed settings documentation
- Backups API - Detailed backup operations
- Logs API - Detailed log operations
- Collections API - Collection management