Vite Environment Variables
This example showcases how IC Reactor integrates with Vite’s environment variable system and the local icp-cli environment to automatically manage canister IDs and network configurations.
Features Demonstrated
Section titled “Features Demonstrated”- Automatic Injection: Canister IDs are automatically detected from the local environment and injected into the frontend.
- Fixed Overrides: Use
canisterIdin the Vite plugin config when you want a specific canister ID to override the auto-detected development value. - Seamless Local Dev: Run
icp deployand your frontend immediately knows where to find the canisters. - Client Configuration:
ClientManagerreads the plugin’sic_envcookie automatically here — canister IDs and root key alike need no option to switch on, because the dev server is a local host and that is where the cookie is trusted. On a custom domain or mainnet it is not read at all.
Live Preview
Section titled “Live Preview”Implementation
Section titled “Implementation”The ClientManager needs no extra configuration. The dev server is served from
a local host and the agent talks to the local replica, so ClientManager
adopts the root key the ic_env cookie carries, and a reactor built without a
canisterId takes its ID from the cookie. On a page served from any other host
the cookie’s canister IDs are refused — a reactor with no configured
canisterId throws there rather than trusting it — and its root key is used
only while the agent host is itself a local replica, unless you pass
allowEnvConfig: true:
import { ClientManager } from "@ic-reactor/react"import { QueryClient } from "@tanstack/react-query"
export const queryClient = new QueryClient()
/** * IC Reactor Client Manager * * Auto-generated by @ic-reactor/codegen */export const clientManager = new ClientManager({ queryClient,})The Vite plugin then ensures these variables are available during development by setting an ic_env cookie:
import { defineConfig } from "vite"import { icReactor } from "@ic-reactor/vite-plugin"
export default defineConfig({ plugins: [ icReactor({ // Generate where the app imports from. The defaults are // outDir "src/declarations" + clientManagerPath "../../clients", which // line up only when the ClientManager sits at `src/clients`. outDir: "./src/lib/canisters", canisters: [ { name: "backend", didFile: "./declarations/backend.did", clientManagerPath: "../../clients", }, ], // Enabled by default injectEnvironment: true, }), ],})