关于 encore-secret
为 Encore 应用介绍密钥的声明、读取和管理方式,适用于需要按环境存储敏感配置的开发者。支持本地覆盖,避免将密钥值提交到代码库。
主要功能
- 01按包级声明密钥
- 02通过函数调用读取密钥
- 03按环境类型设置密钥
- 04使用本地文件覆盖密钥
适用场景
- 01为 API 请求提供令牌
- 02存储 Webhook 签名密钥
- 03在开发和生产环境使用不同密钥
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ encoredev/ skills --skill encore-secret安装后在 Claude Code 中输入/encore-secret确认已加载。
详细介绍
Encore 密钥
说明
密钥是由 Encore 管理、按环境隔离的加密值。在包级别调用 secret(name) 声明密钥,并通过调用返回的函数读取密钥。
import { secret } from "encore.dev/config";
// Package-level declaration
const stripeKey = secret("StripeSecretKey");
// Read inside a handler
async function chargeCustomer() {
const key = stripeKey(); // <-- function call returns the value
const stripe = new Stripe(key);
// ...
}
密钥名称在整个应用中全局唯一(同一个名称在任何地方都对应同一个值)。
设置值
# Set per environment type
encore secret set --type prod StripeSecretKey
encore secret set --type dev StripeSecretKey
encore secret set --type local StripeSecretKey
环境类型:production(别名 prod)、development(别名 dev)、preview(别名 pr)、local。
本地覆盖
在本地开发时,无需通过 encore secret set 设置密钥,只需在仓库根目录创建 .secrets.local.cue 文件(并将其添加到 gitignore):
StripeSecretKey: "sk_test_local_..."
GitHubAPIToken: "ghp_local_..."
常见用法模式
// HTTP headers
const githubToken = secret("GitHubAPIToken");
const resp = await fetch("https://api.github.com/user", {
headers: { Authorization: `token ${githubToken()}` },
});
// Webhook signature verification
const stripeWebhookSecret = secret("StripeWebhookSecret");
stripe.webhooks.constructEvent(rawBody, sig, stripeWebhookSecret());
// Connecting to a third-party SDK
const openaiKey = secret("OpenAIKey");
const openai = new OpenAI({ apiKey: openaiKey() });
指南
- 始终在包级别声明
secret(...),不要在函数内声明。 - 通过函数调用读取密钥:
stripeKey(),而不是stripeKey。 - 使用
encore secret set --type <env>为每个环境设置不同的值。 - 切勿提交密钥值;使用
.secrets.local.cue进行本地覆盖,并将其添加到 gitignore。 - 对于 Webhook 签名密钥,请参阅
encore-webhook技能。
评论
支持 Markdown