AuthenticationError
modal.AuthenticationError
Stack trace
modal.AuthenticationError: Authentication token not found. Please set your Modal API token in the environment variable MODAL_API_TOKEN.
Why it happens
Modal requires an API token for authentication on every request. This error occurs when the token is missing, misspelled, or not loaded from environment variables, preventing authorized access.
Detection
Check for modal.AuthenticationError exceptions during client initialization or API calls, and verify the MODAL_API_TOKEN environment variable is set before running your app.
Causes & fixes
MODAL_API_TOKEN environment variable is not set or is empty
Set the MODAL_API_TOKEN environment variable with your valid Modal API token before running your Python script.
Environment variable name is misspelled or incorrectly referenced in code
Ensure your code and environment use the exact variable name MODAL_API_TOKEN with correct casing.
Running code in an environment where environment variables are not loaded (e.g., IDE or container)
Configure your IDE, container, or deployment environment to load environment variables properly, or explicitly set MODAL_API_TOKEN in the runtime environment.
Code: broken vs fixed
import modal
client = modal.Client() # This line raises AuthenticationError if token missing
print("Client initialized") import os
import modal
os.environ["MODAL_API_TOKEN"] = "your_actual_token_here" # Set your token securely
client = modal.Client() # Now initializes without error
print("Client initialized") Workaround
Catch modal.AuthenticationError and prompt the user to set the MODAL_API_TOKEN environment variable or load it dynamically from a secure source at runtime.
Prevention
Always configure and verify your environment variables for Modal API tokens before deployment, and use secure secret management to avoid missing tokens.