New APINew API
User GuideInstallationAPI ReferenceAI ApplicationsSkillsHelp & SupportBusiness Cooperation

Environment Variable Configuration Guide

This document lists all environment variables supported by New API and explains how to configure them. You can set these variables to customize system behavior.

Tip

New API can read environment variables from a .env file. Use .env.example as a template and rename it to .env before use.

Basic Configuration

Environment VariableDescriptionDefaultExample
PORTPort the service listens on3000PORT=8080
TZTime zone-TZ=America/New_York
VERSIONOverrides the runtime version number-VERSION=1.2.3

Database Configuration

Environment VariableDescriptionDefaultExample
SQL_DSNDatabase connection stringSQLite (one-api.db)PostgreSQL (recommended) SQL_DSN=postgresql://root:123456@postgres:5432/new-api | MySQL SQL_DSN=root:123456@tcp(localhost:3306)/new-api
SQL_MAX_IDLE_CONNSMaximum number of idle connections in the pool100SQL_MAX_IDLE_CONNS=50
SQL_MAX_OPEN_CONNSMaximum number of open connections in the pool1000SQL_MAX_OPEN_CONNS=500
SQL_MAX_LIFETIMEMaximum connection lifetime (seconds)60SQL_MAX_LIFETIME=120
LOG_SQL_DSNConnection string for a separate database that stores the log table-LOG_SQL_DSN=postgresql://root:123456@postgres:5432/oneapi_logs
SQLITE_PATHSQLite database pathone-api.dbSQLITE_PATH=/var/lib/new-api/new-api.db

Database Recommendation

PostgreSQL is recommended for production. MySQL remains a compatible option. If SQL_DSN is unset, New API uses SQLite, which is better suited to local development and testing.

Cache Configuration

Environment VariableDescriptionDefaultExample
REDIS_CONN_STRINGRedis connection string-REDIS_CONN_STRING=redis://default:redispw@localhost:6379
REDIS_POOL_SIZERedis connection pool size10REDIS_POOL_SIZE=20
MEMORY_CACHE_ENABLEDEnables in-memory caching (automatically enabled when Redis is enabled)falseMEMORY_CACHE_ENABLED=true
SYNC_FREQUENCYCache synchronization interval and maximum session cache staleness (seconds) in deployments with a separate Redis instance per node. Other nodes check for synchronization tasks roughly every 3 seconds. This setting controls the fallback full reload interval.60SYNC_FREQUENCY=60
BATCH_UPDATE_ENABLEDEnables batching of database updatesfalseBATCH_UPDATE_ENABLED=true
BATCH_UPDATE_INTERVALInterval for batching updates (seconds)5BATCH_UPDATE_INTERVAL=10

REDIS_CONN_STRING must point to a single Redis-compatible endpoint, with credentials included directly in the URI. New API has no built-in support for parsing Redis Cluster or Sentinel node lists. For high availability, use a managed service or proxy that exposes a single compatible endpoint.

The database is the sole source of truth for dashboard session state. The TTL of a session hash in Redis is the lesser of the session’s remaining lifetime and the effective SYNC_FREQUENCY. Reads leave the TTL unchanged. A delayed cache write for an active session uses only the time remaining in the observation window that began when the database was read. This prevents the entry from receiving a full TTL after the revocation tombstone expires.

Multi-Node and Security Configuration

Environment VariableDescriptionDefaultExample
SESSION_SECRETSession secret (required for multi-node deployments)-SESSION_SECRET=your_session_secret
CRYPTO_SECRETHMAC secret for cache keys. Nodes sharing Redis must use the same effective value.Uses SESSION_SECRETCRYPTO_SECRET=your_crypto_secret
FRONTEND_BASE_URLFrontend base URL. Secondary nodes redirect requests for unmatched routes to this address.-FRONTEND_BASE_URL=https://<your-newapi-domain>
NODE_TYPENode typemasterNODE_TYPE=slave
TLS_INSECURE_SKIP_VERIFYSkips TLS certificate verification globallyfalseTLS_INSECURE_SKIP_VERIFY=true
TRUSTED_REDIRECT_DOMAINSComma-separated list of trusted redirect domains-TRUSTED_REDIRECT_DOMAINS=example.com,api.example.com
TRUSTED_PROXIESComma-separated list of trusted reverse proxy IP addresses or CIDR ranges. Set to none to trust no proxies. If a proxy’s address is outside the trusted ranges, all requests from it are counted against the proxy’s IP address.When unset or empty, trusts loopback, private network ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16), and IPv6 unique local addresses (ULAs)TRUSTED_PROXIES=203.0.113.10,10.1.0.0/16
NODE_NAMENode name used to identify each instance. Use a unique name for each instance.Uses the operating system hostname when unsetNODE_NAME=node-1
PASSWORD_LOGIN_ENCRYPTION_ENABLEDEnables encryption of passwords in transit. New API reads this setting at startup, so changes require a restart. Use the same value on all nodes.falsePASSWORD_LOGIN_ENCRYPTION_ENABLED=true

SESSION_SECRET Requirements

New API refuses to start if SESSION_SECRET is set to random_string. All nodes in a multi-node deployment must use the same secret.

Cluster Deployment

For instructions on setting up a complete cluster with these environment variables, see the Cluster Deployment Guide.

User and Token Configuration

Environment VariableDescriptionDefaultExample
GENERATE_DEFAULT_TOKENGenerates an initial token for newly registered usersfalseGENERATE_DEFAULT_TOKEN=true
NOTIFICATION_LIMIT_DURATION_MINUTENotification rate limit window (minutes)10NOTIFICATION_LIMIT_DURATION_MINUTE=15
NOTIFY_LIMIT_COUNTMaximum number of notifications within the specified window2NOTIFY_LIMIT_COUNT=3

Request Rate Limit Configuration

Environment VariableDescriptionDefaultExample
GLOBAL_API_RATE_LIMIT_ENABLEEnables global API rate limitingtrueGLOBAL_API_RATE_LIMIT_ENABLE=false
GLOBAL_API_RATE_LIMITGlobal API rate limit per IP address360GLOBAL_API_RATE_LIMIT=100
GLOBAL_API_RATE_LIMIT_DURATIONGlobal API rate limit window (seconds)180GLOBAL_API_RATE_LIMIT_DURATION=120
GLOBAL_WEB_RATE_LIMIT_ENABLEEnables global web rate limitingtrueGLOBAL_WEB_RATE_LIMIT_ENABLE=false
GLOBAL_WEB_RATE_LIMITGlobal web rate limit per IP address120GLOBAL_WEB_RATE_LIMIT=30
GLOBAL_WEB_RATE_LIMIT_DURATIONGlobal web rate limit window (seconds)180GLOBAL_WEB_RATE_LIMIT_DURATION=120
CRITICAL_RATE_LIMIT_ENABLEEnables rate limiting for critical operationstrueCRITICAL_RATE_LIMIT_ENABLE=false
CRITICAL_RATE_LIMITMaximum number of critical operations per window20CRITICAL_RATE_LIMIT=10
CRITICAL_RATE_LIMIT_DURATIONRate limit window for critical operations (seconds)1200CRITICAL_RATE_LIMIT_DURATION=600
GLOBAL_STATIC_RATE_LIMIT_ENABLEEnables global rate limiting for static assetsfalseGLOBAL_STATIC_RATE_LIMIT_ENABLE=true
GLOBAL_STATIC_RATE_LIMITGlobal rate limit for static assets per IP address1000GLOBAL_STATIC_RATE_LIMIT=500
GLOBAL_STATIC_RATE_LIMIT_DURATIONGlobal rate limit window for static assets (seconds)180GLOBAL_STATIC_RATE_LIMIT_DURATION=120
SEARCH_RATE_LIMIT_ENABLEEnables search rate limitingtrueSEARCH_RATE_LIMIT_ENABLE=false
SEARCH_RATE_LIMITMaximum number of searches per window10SEARCH_RATE_LIMIT=20
SEARCH_RATE_LIMIT_DURATIONSearch rate limit window (seconds)60SEARCH_RATE_LIMIT_DURATION=120

Relay and Proxy Configuration

Environment VariableDescriptionDefaultExample
RELAY_TIMEOUTRelay request timeout (seconds). Set to 0 for no timeout.0RELAY_TIMEOUT=60
STREAMING_TIMEOUTTimeout for a single streaming response (seconds)300STREAMING_TIMEOUT=120
RELAY_MAX_IDLE_CONNSMaximum number of idle connections in the relay HTTP client pool500RELAY_MAX_IDLE_CONNS=1000
RELAY_MAX_IDLE_CONNS_PER_HOSTMaximum number of idle connections per host in the relay HTTP client pool100RELAY_MAX_IDLE_CONNS_PER_HOST=200
MAX_FILE_DOWNLOAD_MBMaximum file download size (MB)64MAX_FILE_DOWNLOAD_MB=128
MAX_REQUEST_BODY_MBMaximum request body size after decompression (MB). Helps prevent zip bombs and out-of-memory errors.128MAX_REQUEST_BODY_MB=256
STREAM_SCANNER_MAX_BUFFER_MBMaximum SSE stream scanner buffer size (MB)128STREAM_SCANNER_MAX_BUFFER_MB=128

RELAY_TIMEOUT Configuration Warning

Use caution when setting RELAY_TIMEOUT. A timeout that is too short can cause billing discrepancies.

  • The upstream API may complete and charge for a request even if the local system times out before recording the charge.

  • This billing discrepancy may result in a financial loss for the system.

  • Leave this variable unset unless you know what you are doing.

Channel Management Configuration

Environment VariableDescriptionDefaultExample
CHANNEL_UPDATE_FREQUENCYInterval for updating channel balances (minutes). The “Batch Balance Update” background task performs the updates.- (disabled when unset)CHANNEL_UPDATE_FREQUENCY=1440
CHANNEL_TEST_FREQUENCYInterval for periodic channel checks (minutes). Overrides the database setting.- (uses the database setting when unset)CHANNEL_TEST_FREQUENCY=1440
POLLING_INTERVALRequest polling interval (seconds)0POLLING_INTERVAL=5
CHANNEL_TEST_ENABLEDOverrides the “Periodic Channel Testing” toggle in the UI when set- (uses the database setting when unset)CHANNEL_TEST_ENABLED=false

Upstream Model Synchronization for Channels

Environment VariableDescriptionDefaultExample
CHANNEL_UPSTREAM_MODEL_UPDATE_TASK_ENABLEDEnables periodic synchronization of upstream providers’ model liststrueCHANNEL_UPSTREAM_MODEL_UPDATE_TASK_ENABLED=false
CHANNEL_UPSTREAM_MODEL_UPDATE_TASK_INTERVAL_MINUTESModel list synchronization interval (minutes)30CHANNEL_UPSTREAM_MODEL_UPDATE_TASK_INTERVAL_MINUTES=60
CHANNEL_UPSTREAM_MODEL_UPDATE_MIN_CHECK_INTERVAL_SECONDSMinimum interval between checks for a single channel (seconds)300CHANNEL_UPSTREAM_MODEL_UPDATE_MIN_CHECK_INTERVAL_SECONDS=600

Model and Request Processing Configuration

Environment VariableDescriptionDefaultExample
FORCE_STREAM_OPTIONOverrides the client’s stream_options parameter to always retrieve usage data for streaming responsestrueFORCE_STREAM_OPTION=false
CountTokenEnables local token countingtrueCountToken=false
GET_MEDIA_TOKENCounts image and audio tokens in streaming modetrueGET_MEDIA_TOKEN=false
GET_MEDIA_TOKEN_NOT_STREAMCounts image and audio tokens in non-streaming modefalseGET_MEDIA_TOKEN_NOT_STREAM=true

Asynchronous Task Configuration

Environment VariableDescriptionDefaultExample
UPDATE_TASKEnables polling for asynchronous task updates (MJ, Suno, etc.)trueUPDATE_TASK=false
TASK_QUERY_LIMITMaximum number of tasks queried per polling cycle1000TASK_QUERY_LIMIT=500
TASK_TIMEOUT_MINUTESAsynchronous task timeout (minutes). When a task times out, New API marks it as failed and issues a refund. Set to 0 to disable the timeout.4320TASK_TIMEOUT_MINUTES=720
TASK_PRICE_PATCHTask pricing override. Listed models are billed per request only. Separate model names with commas.-TASK_PRICE_PATCH=sora-2,sora-2-pro
TASK_PLUGIN_ENABLEDInitial value of the global “Enable Plugins” toggle. Once the toggle is saved in the UI, the saved value takes precedence.trueTASK_PLUGIN_ENABLED=false
TASK_POLL_MAX_FAILURESNumber of consecutive unrecognized or transient polling failures before New API marks a task as failed and issues a refund20TASK_POLL_MAX_FAILURES=10

Model-Specific Configuration

Environment VariableDescriptionDefaultExample
AZURE_DEFAULT_API_VERSIONDefault API version for Azure channels2025-04-01-previewAZURE_DEFAULT_API_VERSION=2023-05-15
COHERE_SAFETY_SETTINGCohere model safety settingNONECOHERE_SAFETY_SETTING=CONTEXTUAL
DIFY_DEBUGEnables workflow and node information in Dify channel outputtrueDIFY_DEBUG=false

Subscription Cache Configuration

Environment VariableDescriptionDefaultExample
SUBSCRIPTION_PLAN_CACHE_TTLSubscription plan cache TTL (seconds)300SUBSCRIPTION_PLAN_CACHE_TTL=600
SUBSCRIPTION_PLAN_INFO_CACHE_TTLSubscription plan details cache TTL (seconds)120SUBSCRIPTION_PLAN_INFO_CACHE_TTL=300
SUBSCRIPTION_PLAN_CACHE_CAPMaximum capacity of the subscription plan cache5000SUBSCRIPTION_PLAN_CACHE_CAP=10000
SUBSCRIPTION_PLAN_INFO_CACHE_CAPMaximum capacity of the subscription plan details cache10000SUBSCRIPTION_PLAN_INFO_CACHE_CAP=20000

Other Configuration

Environment VariableDescriptionDefaultExample
ERROR_LOG_ENABLEDRecords error logs and displays them in the frontendfalseERROR_LOG_ENABLED=true
SMTP_STARTTLS_ENABLEControls whether “SMTP Encryption Method” is initially set to STARTTLS for outgoing email. The legacy name SMTP_STARTTLS_ENABLED is still supported.falseSMTP_STARTTLS_ENABLE=true
SMTP_INSECURE_SKIP_VERIFYInitial value of “Skip SMTP TLS Certificate Verification” for outgoing email. The legacy name SMTP_TLS_INSECURE_SKIP_VERIFY is still supported.falseSMTP_INSECURE_SKIP_VERIFY=true

Analytics

Environment VariableDescriptionDefaultExample
UMAMI_WEBSITE_IDUmami website ID-UMAMI_WEBSITE_ID=xxxx-xxxx
UMAMI_SCRIPT_URLUmami script URLhttps://analytics.umami.is/script.jsUMAMI_SCRIPT_URL=https://umami.example.com/script.js
GOOGLE_ANALYTICS_IDGoogle Analytics 4 website measurement ID-GOOGLE_ANALYTICS_ID=G-XXXXXXX

Metadata Synchronization

Environment VariableDescriptionDefaultExample
SYNC_UPSTREAM_BASEUpstream base URL for model and provider metadatahttps://basellm.github.io/llm-metadataSYNC_UPSTREAM_BASE=https://mirror.example.com/llm-metadata
SYNC_HTTP_TIMEOUT_SECONDSHTTP timeout for synchronization (seconds)10SYNC_HTTP_TIMEOUT_SECONDS=15
SYNC_HTTP_RETRYNumber of synchronization retries3SYNC_HTTP_RETRY=5
SYNC_HTTP_MAX_MBMaximum response body size (MB)10SYNC_HTTP_MAX_MB=20

Frontend Configuration

Environment VariableDescriptionDefaultExample
VITE_REACT_APP_SERVER_URLBackend base URL for frontend requests (set at build time)-VITE_REACT_APP_SERVER_URL=https://api.example.com

Build-Time Variable

Vite injects VITE_REACT_APP_SERVER_URL when building the frontend. Changing it requires rebuilding the frontend.

Pyroscope Continuous Profiling

Environment VariableDescriptionDefaultExample
PYROSCOPE_URLPyroscope server URL. Leave blank to disable profiling.-PYROSCOPE_URL=http://pyroscope:4040
PYROSCOPE_APP_NAMEApplication name reported to Pyroscopenew-apiPYROSCOPE_APP_NAME=my-api
PYROSCOPE_BASIC_AUTH_USERPyroscope Basic Auth username-PYROSCOPE_BASIC_AUTH_USER=admin
PYROSCOPE_BASIC_AUTH_PASSWORDPyroscope Basic Auth password-PYROSCOPE_BASIC_AUTH_PASSWORD=secret
HOSTNAMEHostname label reported to Pyroscopenew-apiHOSTNAME=node-1
PYROSCOPE_MUTEX_RATEMutex profiling sampling rate5PYROSCOPE_MUTEX_RATE=10
PYROSCOPE_BLOCK_RATEBlock profiling sampling rate5PYROSCOPE_BLOCK_RATE=10

LinuxDo OAuth

The defaults work for most deployments.

Environment VariableDescriptionDefaultExample
LINUX_DO_TOKEN_ENDPOINTLinuxDo token endpointhttps://connect.linux.do/oauth2/tokenLINUX_DO_TOKEN_ENDPOINT=https://connect.linux.do/oauth2/token
LINUX_DO_USER_ENDPOINTLinuxDo user endpointhttps://connect.linux.do/api/userLINUX_DO_USER_ENDPOINT=https://connect.linux.do/api/user

Debugging

Environment VariableDescriptionDefaultExample
DEBUGEnables debug mode, including GORM debug outputfalseDEBUG=true
GIN_MODEGin runtime modereleaseGIN_MODE=debug
ENABLE_PPROFEnables pprof profiling on port 8005falseENABLE_PPROF=true

Deprecated Environment Variables

The following environment variables are deprecated. Use the corresponding options in the System Settings UI.

Environment VariableReplacement
GEMINI_MODEL_MAPConfigure under System Settings → Model Settings
GEMINI_SAFETY_SETTINGConfigure under System Settings → Model Settings
GEMINI_VISION_MAX_IMAGE_NUMConfigure under System Settings → Model Settings

Multi-Node Deployment Example

All nodes in a multi-node deployment must use the same remote database and SESSION_SECRET. Nodes can share one Redis instance, run separate Redis instances, or run without Redis. For details on how these configurations behave, see the Cluster Deployment Guide.

Primary Node Configuration

# 数据库配置 - 使用远程数据库
SQL_DSN=postgresql://newapi:password@db-server:5432/oneapi

# 安全配置
SESSION_SECRET=your_unique_session_secret
CRYPTO_SECRET=your_unique_crypto_secret

# Redis缓存配置(也可使用本节点 Redis,或省略以禁用 Redis)
REDIS_CONN_STRING=redis://default:password@redis-server:6379

Secondary Node Configuration

# 数据库配置 - 使用相同的远程数据库
SQL_DSN=postgresql://newapi:password@db-server:5432/oneapi

# 安全配置 - SESSION_SECRET 与主节点相同;共享 Redis 时 CRYPTO_SECRET 也相同
SESSION_SECRET=your_unique_session_secret
CRYPTO_SECRET=your_unique_crypto_secret

# Redis缓存配置 - 可与主节点相同,也可指向本节点独立 Redis
REDIS_CONN_STRING=redis://default:password@redis-slave-node:6379

# 节点类型设置
NODE_TYPE=slave

# 可选:前端基础URL
# FRONTEND_BASE_URL=https://<your-newapi-domain>

# 可选:同步频率
SYNC_FREQUENCY=60

Complete Cluster Configuration

This example uses a separate Redis instance for each node. To share a Redis instance, set the same REDIS_CONN_STRING on both nodes. Without Redis, session validation queries the shared database directly. For the complete configuration and consistency guarantees, see the Cluster Deployment Guide.

Environment Variables in Docker Compose

The following example shows how to set environment variables in a Docker Compose configuration file.

services:
  new-api:
    image: calciumion/new-api:latest
    environment:
      - TZ=Asia/Shanghai
      - SQL_DSN=postgresql://newapi:123456@postgres:5432/oneapi
      - REDIS_CONN_STRING=redis://default:redispw@redis:6379
      - SESSION_SECRET=your_unique_session_secret
      - CRYPTO_SECRET=your_unique_crypto_secret
      - MEMORY_CACHE_ENABLED=true
      - GENERATE_DEFAULT_TOKEN=true
      - STREAMING_TIMEOUT=120
      - CHANNEL_UPDATE_FREQUENCY=1440

For the complete Docker Compose configuration and additional environment variable options, see the Docker Compose Configuration Guide.

How is this guide?

Last updated on