How to pass environment (.env) variables to frontend? #2873
Replies: 4 comments 7 replies
-
Also, With all respect, is there any way to change environment variables at runtime (running the build) in react-tauri ? Thanks in advance |
Beta Was this translation helpful? Give feedback.
-
@NikolaGrgic You should be able to do that by naming your env variable with So for instance you can create a |
Beta Was this translation helpful? Give feedback.
-
I just implemented a similar thing in my react + tauri application. This is my fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![get_environment_variable])
.run(tauri::generate_context!())
.expect("error while running tauri application");
} Here, #[tauri::command]
fn get_environment_variable (name: &str) -> String {
std::env::var(name).unwrap_or_else(|_| "".to_string())
} For your use case, you can expose a similar function with no parameters which just returns your "dynamically generated variable" invoke("get_environment_variable", { name: "params" })
.then((hostIp) => {
if (hostIp) serverRootUrl = "http://" + hostIp + ":5000";
else serverRootUrl = defaultServerUrl;
})
.catch(console.log); My case was similar because if the server URL is not loaded, there is no use of launching the app. So, I waited for a while using Looks a bit hacky, but it is what I did |
Beta Was this translation helpful? Give feedback.
-
Just came across this recently, here're several ways I found: 1. Using #[tauri::command]
fn get_env(name: &str) -> String {
std::env::var(String::from(name)).unwrap_or(String::from(""))
} Then in typescript: import { invoke } from "@tauri-apps/api/core";
function get_env(name: string) {
return await invoke("get_env", { name });
} 2. Using Vite Only with import.meta.env.VITE_DEVELOPER_MINDSET 3. Using SvelteKit In SSG mode only and only starting with import * as env from "$env/static/public";
console.log(import.meta.env.PUBLIC_DEVELOPER_MINDSET); // works 4. Pure Rust Install crate: Then in your rust code, load from dotenv::dotenv().ok(); Or using macro: #[macro_use]
extern crate dotenv_codegen; And then in rust you can use println!("{}", dotenv!("DEVELOPER_MINDSET")); There are couple more options on how to connect pulling and embedded environment variables inside backend and frontend of the Tauri app in my tutorial. |
Beta Was this translation helpful? Give feedback.
-
Hey all,
I have a dynamically-generated variable created in the Rust backend that I need to pass down as an environment variable to the React frontend. Is there any way to pass variables to create-react-app before Tauri launches the application?
Thanks in advance.
Beta Was this translation helpful? Give feedback.
All reactions