Secrets Module (@microfn/secret)
@microfn/secret
Section titled “@microfn/secret”The @microfn/secret
module allows you to access secrets and environment variables configured in your workspace. Use it to retrieve API keys, tokens, database credentials, and other sensitive configuration values without hardcoding them in your code.
Import
Section titled “Import”import secret from "@microfn/secret";
Quick Snippet
Section titled “Quick Snippet”// Get a secret valueconst apiKey = await secret.get("API_KEY");
// Get a required secret, which throws an error if not foundconst dbUrl = await secret.getRequired("DATABASE_URL");
Examples
Section titled “Examples”Here are a few useful things you can do with @microfn/secret
:
1. Use an API key
Section titled “1. Use an API key”Securely access an API key to make authenticated requests.
import secret from "@microfn/secret";
export default async function main() { const apiKey = await secret.get("STRIPE_API_KEY"); if (!apiKey) { return { error: "API key not configured." }; }
const response = await fetch("https://api.stripe.com/v1/charges", { headers: { Authorization: `Bearer ${apiKey}` } });
return { success: response.ok };}
2. Connect to a database
Section titled “2. Connect to a database”Build a database connection string from multiple required secrets.
import secret from "@microfn/secret";
export default async function main() { try { const host = await secret.getRequired("DB_HOST"); const user = await secret.getRequired("DB_USER"); const password = await secret.getRequired("DB_PASSWORD"); const dbName = await secret.get("DB_NAME", "default_db");
const connectionString = `postgres://${user}:${password}@${host}/${dbName}`; // ... connect to database
return { connected: true }; } catch (error) { return { error: "Database configuration is incomplete." }; }}
3. Manage feature flags
Section titled “3. Manage feature flags”Enable or disable features in your application without deploying new code.
import secret from "@microfn/secret";
export default async function main() { const newSearchEnabled = await secret.get("FEATURE_NEW_SEARCH", "false") === "true";
if (newSearchEnabled) { // run new search logic return { feature: "new-search" }; } else { // run old search logic return { feature: "old-search" }; }}