Skip to content

Environment Variables & Secrets

Microfn provides a secure way to store and access sensitive configuration values like API keys, database credentials, and other secrets. These values are encrypted at rest and only accessible to your functions at runtime.

  1. Store secrets in your workspace through the dashboard or API
  2. Secrets are encrypted and stored securely
  3. At runtime, secrets are injected as environment variables with SECRET_ prefix
  4. Access via the @microfn/secret module in your functions
  5. Never exposed in logs, error messages, or function responses
  1. Navigate to your workspace
  2. Go to Settings → Secrets
  3. Click “Add Secret”
  4. Enter key and value
  5. Click Save
import secret from "@microfn/secret";
export default async function main() {
// Get a secret (returns undefined if not found)
const apiKey = await secret.get("API_KEY");
// Get with default value
const timeout = await secret.get("TIMEOUT", "5000");
// Get required secret (throws if not found)
const dbUrl = await secret.getRequired("DATABASE_URL");
// Check if secret exists
const hasStripeKey = await secret.has("STRIPE_KEY");
// Get all secrets with prefix
const awsSecrets = await secret.getWithPrefix("AWS_");
return { configured: true };
}

While not recommended, you can access secrets directly:

export default async function main() {
// Secrets are prefixed with SECRET_
const apiKey = process.env.SECRET_API_KEY;
// Not recommended - use @microfn/secret module instead
return { hasKey: !!apiKey };
}

Use clear and descriptive names for your secrets.

import secret from "@microfn/secret";
export default async function main(input) {
const apiKey = await secret.getRequired("OPENAI_API_KEY");
const response = await fetch("https://api.openai.com/v1/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: input.prompt }]
})
});
return await response.json();
}
import secret from "@microfn/secret";
import { createConnection } from 'mysql2/promise';
export default async function main(input) {
// Build connection string from secrets
const connection = await createConnection({
host: await secret.getRequired("DB_HOST"),
port: parseInt(await secret.get("DB_PORT", "3306")),
user: await secret.getRequired("DB_USER"),
password: await secret.getRequired("DB_PASSWORD"),
database: await secret.getRequired("DB_NAME")
});
const [rows] = await connection.execute(
'SELECT * FROM users WHERE id = ?',
[input.userId]
);
await connection.end();
return { user: rows[0] };
}