Environment Variables

Environment Variables

Overview

Tuono supports environment variables for both the client and server, with hot reload functionality in each scenario.

Key features include:

  • Loading from .env.* files
  • Managing precedence across multiple env files
  • Supporting hot reload on both client and server
  • Bundling client env vars with the TUONO_PUBLIC_ prefix

Usage

Define your environment variables in .env file(s). For example, you can use a .env file and a .env.local file.

# .env
MY_KEY=foo
MY_DUPLICATED_KEY=env
MY_QUOTED_KEY="bar"
TUONO_PUBLIC_MY_PUBLIC_KEY=public_value
# .env.local
MY_DUPLICATED_KEY=local
MY_SECRET=some_secret

Variables set in .env.local will override those in .env. For more information on this behaviour, refer to the modes section.

Client-side

Tuono exposes any environment variable that starts with the TUONO_PUBLIC_ prefix to the client at build time via the import.meta.env object.

Here’s an example of how to use it:

console.log(import.meta.env.TUONO_PUBLIC_SOME_KEY) // "123"
console.log(import.meta.env.DB_PASSWORD) // undefined

⚠️ Note that variables starting with the TUONO_PUBLIC_ prefix will be included in your client bundle, and as such, these variables should not contain any sensitive or secret values.

Server-side

Environment variables are automatically loaded into the Rust environment, allowing you to use them just like you would use any other system environment variable in any other rust codebase.

use std::env;
use tuono_lib::Request;
use tuono_lib::axum::http::StatusCode;

#[tuono_lib::api(GET)]
pub async fn health_check(_req: Request) -> StatusCode {
    println!("{}", env::var("DATABASE_URL").expect("DATABASE_URL not set"));
    StatusCode::OK
}

Mode-Specific Env Files

System environment variables take priority, and are never overridden. After that, precedence is determined by specificity, with the most specific env files taking priority.

.env                # loaded in all cases
.env.local          # loaded in all cases, ignored by git
.env.[mode]         # only loaded in specified mode
.env.[mode].local   # only loaded in specified mode, ignored by git

Caveats, Gotchas and Notes

  • Secrets should only be stored in *.local files, as those are the only files ignored by git.
  • When you create a new env file, it is not automatically loaded. You will have to restart the server for the changes to take effect.
Edit page