static-site
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseStatic Site (Certified Assets)
静态站点(Certified Assets)
What This Is
这是什么
The recipe deploys a static site — a built frontend, docs, or any folder of files — to the certified-assets canister on the Internet Computer, which serves it over HTTP with response certification. The canister certifies every response (certification v2 only, never the escape hatch, no way to turn it off), and a verifying HTTP gateway checks that proof before handing the response to the browser: visitors get content the canister provably committed to, not something altered in transit. Whether the proof is checked depends on the gateway the visitor goes through: verifies, does not (Pitfall 14).
@dfinity/static-siteno_certificationhttps://<canister-id>.icp.nethttps://<canister-id>.raw.icp.netThis is the recommended way to host a frontend on the IC going forward. The recipe bundles a matched pair — the canister and its sync plugin — pinned together by one version. You point it at your build directory; uploads, certifies, and serves.
icp deployThe olderrecipe (the SDK asset canister, configured with@dfinity/asset-canister) is still supported for existing projects but is no longer the recommended path. It is a different canister with a different config format and API — see.ic-assets.json5. To move an existing project over, seereferences/legacy-asset-canister.md.references/migrating-from-asset-canister.md
@dfinity/static-siteno_certificationhttps://<canister-id>.icp.nethttps://<canister-id>.raw.icp.net这是今后在 IC 上托管前端的推荐方式。 recipe 将匹配的一对组件打包在一起——canister 及其 sync plugin——并通过同一版本锁定。你只需将 build 目录指向它; 会上传、认证并提供内容。
icp deploy较旧的recipe(SDK asset canister,使用@dfinity/asset-canister配置)仍受现有项目支持,但已不再是推荐路径。它是一个 不同的 canister,具有不同的配置格式和 API——请参阅.ic-assets.json5。如需迁移现有项目,请参阅references/legacy-asset-canister.md。references/migrating-from-asset-canister.md
Prerequisites
前置条件
- —
icp-cli. The recipe pins the canister + sync-plugin pair, both pre-built, so a plainnpm install -g @icp-sdk/icp-cli/dir/builddeploy needs nothing else.presync - —
ic-wasm. A separate binary, not bundled withnpm install -g @icp-sdk/ic-wasm. This recipe shells out to it only when you set theicp-clifield (the generated build guards onmetadataand fails with "ic-wasm not found"); other official recipes need it unconditionally, so installing both up front is the safe default — see thecommand -v ic-wasmskill.icp-cli - Your frontend's build toolchain (e.g. Node.js >= 22 for a Vite/React app).
- —
icp-cli。recipe 会锁定 canister + sync-plugin 配对,两者均已预构建,因此普通的npm install -g @icp-sdk/icp-cli/dir/build部署不需要其他依赖。presync - —
ic-wasm。这是一个 独立 二进制文件,不包含在npm install -g @icp-sdk/ic-wasm中。只有在设置icp-cli字段时,此 recipe 才会调用它(生成的构建脚本会检查metadata,如果未找到则报“ic-wasm not found”);其他官方 recipe 则无条件需要它,因此预先安装两者是更稳妥的默认选择——请参阅command -v ic-wasmskill。icp-cli - 前端的 build toolchain(例如,Vite/React 应用需要 Node.js >= 22)。
Canister IDs and URLs
Canister ID 与 URL
Static-site canisters are created per-project — there is no global canister ID. After deployment the canister ID is stored in . Managed networks (the local replica) are cache — ; connected networks (mainnet ) are data — .
.icp/<cache|data>/mappings/<environment>.ids.json.icp/cache/mappings/local.ids.jsonic.icp/data/mappings/ic.ids.json| Environment | Browser URL |
|---|---|
| Local | |
| Mainnet | |
| Custom domain | |
静态站点 canister 按项目创建——不存在全局 canister ID。部署后,canister ID 会存储在 中。托管网络(本地 replica)属于 cache — ;已连接的网络(主网 )属于 data — 。
.icp/<cache|data>/mappings/<environment>.ids.json.icp/cache/mappings/local.ids.jsonic.icp/data/mappings/ic.ids.json| 环境 | 浏览器 URL |
|---|---|
| 本地 | |
| 主网 | |
| 自定义域名 | |
icp.yaml Configuration
icp.yaml
配置
icp.yamlyaml
canisters:
- name: frontend
recipe:
type: "@dfinity/static-site@v0.4.3"
configuration:
build:
- npm ci
- npm run build
dir: distCheck the static-site releases for the latest version and pin it in the field. Because the recipe pins a matched canister + plugin pair, there is no separate canister version to choose — the recipe version is the canister version.
typeThe recipe takes four configuration fields:
| Field | Required | Description |
|---|---|---|
| Yes | The single directory of built files to serve. The canister owns its whole URL space, so this is one directory, not a list. Vite → |
| No | Shell commands run before the canister exists to produce |
| No | Shell commands run at sync time, after the canister exists, with deployed canister IDs exported as env vars. Use this to bake a canister ID into a frontend build (see below). |
| No | |
yaml
canisters:
- name: frontend
recipe:
type: "@dfinity/static-site@v0.4.3"
configuration:
build:
- npm ci
- npm run build
dir: dist请查看 static-site releases 获取最新版本,并在 字段中锁定该版本。由于 recipe 会锁定匹配的 canister + plugin 配对,因此 无需单独选择 canister 版本——recipe 版本 就是 canister 版本。
type此 recipe 接受四个配置字段:
| 字段 | 必需 | 说明 |
|---|---|---|
| 是 | 要提供服务的构建文件所在的单一目录。canister 拥有其整个 URL 空间,因此这里是单个目录,而不是列表。Vite → |
| 否 | 在 canister 存在 之前 运行的 Shell 命令,用于生成 |
| 否 | 在 sync 时、canister 已存在 之后 运行的 Shell 命令,已部署的 canister ID 会作为环境变量导出。可用此方式将 canister ID 写入前端构建产物(请参阅下文)。 |
| 否 | 通过 |
Pitfalls
常见陷阱
-
Usingwith the static-site recipe.
.ic-assets.json5is the legacy asset canister's config file. The certified-assets canister does not read it — and because the plugin skips every dotfile and dot-directory (only.ic-assets.json5is exempt, Pitfall 12), a.well-known/in your.ic-assets.json5is not even uploaded. It is silently absent, so SPA fallback, headers, and security policy do nothing. Configure this canister withdirand_redirectsinstead (below)._headers -
Wrong SPA fallback rule. For client-side routing, the fallback is a rewrite in:
_redirects. The/* /index.html 200status is what makes it a rewrite (serve the shell's contents at the requested URL, no visible redirect) so deep links work on fresh load and reload. Do not use a200/301redirect, and do not reach for302— that is a legacy asset-canister setting and has no effect here.enable_aliasing -
Relative asset paths in a SPA. Link assets with absolute paths (), never relative (
/assets/app.js). Under aassets/app.jsrewrite, a relative URL resolves against the client route: at/*the browser requests/dashboard/settings, which/dashboard/settings/assets/app.jsanswers with the HTML shell — producing a confusing MIME-type error instead of loading your script./* -
Expecting/
AssetManagerto work. The certified-assets canister's upload API is@icp-sdk/canisters+upload_chunks, not the SDK asset canister'sexecute_operations/store/create_batch.commit_batchfromAssetManagertargets the legacy canister and does not work against static-site. Uploads happen through the recipe's sync plugin on@icp-sdk/canisters/assets; there is no drop-in JSicp deployequivalent for this canister. (If you need programmatic uploads, you are almost certainly on the legacy canister — see the legacy reference.)AssetManager -
/
_headersin the wrong place. These two files must sit at the root of your_redirects(e.g.dir). They are read as configuration and never served as assets. Put them in yourdist/_redirects(Vite) orpublic/folder so the build copies them intostatic/automatically — a file left at the project root but not copied intodiris simply absent at deploy time.dir -
Setting a reserved header in. The sync plugin rejects these at deploy time with an explanatory error:
_headers,Content-Length,Content-Encoding,ETag,Transfer-Encoding,Accept-Ranges,Content-Range,IC-Certificate,IC-CertificateExpression. To set an asset's media type use the bareLocationform (it routes to asset metadata, not a response header). To redirect, useContent-Type:— a_redirectsheader inLocationwould not redirect (status stays_headers).200 -
Assuming default security headers. Unlike the legacy canister's, the certified-assets canister adds no default headers — no
security_policy: "standard", no CSP, noCache-Control. If you want them, declare them inX-Frame-Options(baseline below). The only headers it manages itself are the certification/serving ones and its_headerscookie.ic_env -
A/
404rule pointing at a large file. An error-page target must be a small, single-chunk file (under ~1.9 MB). Large files are served as certified410range responses that can't carry a 4xx status, so the plugin rejects such a rule at deploy time, naming it. (A206rewrite to a large file is fine.)200 -
Expecting dynamic redirect captures. There is noor
:splat— you can't forward a captured segment (:placeholder). Every certifiable response must be enumerable ahead of time, so/old/:rest → /new/:rest/_redirectssupport only exact paths, a trailing_headerssubtree wildcard, and fixed destinations./* -
Switching an existing project from the legacy asset canister to static-site. Repointingat
recipe:and running a plain@dfinity/static-sitefails before anything is installed: these are two unrelated canisters with unrelated Candid interfaces, so icp-cli's pre-install check aborts withicp deploy. RunCandid interface compatibility check failed: '<canister>' … You are making a BREAKING changeinstead. That replaces the wasm with the certified-assets canister, discards the old stable memory — every legacy asset, permission, andicp deploy --mode reinstall-derived setting is gone — and leaves the canister with empty state, after which the sync plugin uploads your whole.ic-assets.json5from scratch. Deploying static-site as a brand-new canister avoids the question entirely. Do not silence the check withdir: that pushes the in-place upgrade through onto stable memory certified-assets cannot read, leaving a live canister that serves nothing. See the migration reference.--yes -
Assuming a recipe version bump re-installs itself. Moving between certified-assets' own releases is gentler than the legacy switch above — the Candid interface is stable across a release series, so nothing blocks the deploy — but a breaking bump still needs a reinstall you run yourself. The canister and plugin are version-locked, so after bumping the recipeupgrades in place and the sync plugin then refuses, reporting
icp deployplus the fix:assets canister version mismatch: canister is X, this plugin is Yfor a patch bump (state preserved) oricp canister install --mode upgradefor a breaking (pre-1.0 minor, post-1.0 major) bump, which wipes state so the next sync re-uploads every asset and redirect rule. (icp canister install --mode reinstall→v0.3.xis breaking: reinstall, thenv0.4.0.icp deploy→v0.4.xis a patch: upgrade, thenv0.4.3.) A failed sync right after a version bump is expected — this, not a bug.icp deploy -
is uploaded automatically — no config needed. The plugin skips dotfiles and dot-directories except
.well-known/, which it traverses normally. So.well-known/is served atdir/.well-known/ic-domainswith no extra setting. (This is the opposite of the legacy canister, which needed an explicit/.well-known/ic-domainsun-ignore rule.).ic-assets.json5 -
Access protection ordering. The recipe'sinstalls the canister and syncs assets together, so a plain deploy-then-
icp deploybriefly serves your content publicly. For a brand-new private app, enable protection before your real assets are synced — deploy aenable_protectioncontaining onlydir,login.html, then deploy the full site — so assets are never world-readable. The login page must be fully self-contained (inline CSS/JS,enable_protectionURIs) — it is the only gate-exempt path, and any external subresource it references would itself be gated. See Access protection.data: -
Sharing or linking aURL.
raw.icp.netserves the same site as<canister-id>.raw.icp.net, but the gateway forwards responses without checking the certificate, so the visitor gets no more assurance than from an ordinary web host. There is no canister setting to refuse<canister-id>.icp.netrequests (unlike the legacy canister'sraw): the only clue is the unauthenticatedallow_raw_accessheader, and which hostnames verify is a gateway deployment detail, not protocol. Link toHost(or a custom domain on a verifying gateway) and treathttps://<canister-id>.icp.netas a debugging tool only. With access protection on, arawURL is actively dangerous: the redirect and login page arrive unverified, so a non-verifying gateway could serve a fake login form and harvest tokens. The access cookie is host-only, so a session on the certified host does not carry over toraw.raw
-
在 static-site recipe 中使用。
.ic-assets.json5是 legacy asset canister 的配置文件。certified-assets canister 不会读取它——而且由于 plugin 会跳过每个 dotfile 和 dot-directory(只有.ic-assets.json5除外,见陷阱 12),位于.well-known/中的dir甚至不会被上传。它会被静默忽略,因此 SPA fallback、标头和安全策略都不会生效。请改用.ic-assets.json5和_redirects配置此 canister(见下文)。_headers -
使用错误的 SPA fallback 规则。 对于客户端路由,fallback 必须是中的 rewrite:
_redirects。/* /index.html 200状态码使其成为 rewrite(在请求的 URL 提供 shell 内容,不产生可见重定向),因此深层链接在首次加载和刷新时都能正常工作。不要使用200/301redirect,也不要使用302——后者是 legacy asset-canister 的设置,在这里不起作用。enable_aliasing -
在 SPA 中使用相对资源路径。 应使用 绝对 路径链接资源(),绝不要使用相对路径(
/assets/app.js)。在assets/app.jsrewrite 下,相对 URL 会根据 客户端路由 进行解析:在/*处,浏览器会请求/dashboard/settings,而/dashboard/settings/assets/app.js会以 HTML shell 响应它,最终产生令人困惑的 MIME 类型错误,而不是正常加载脚本。/* -
以为/
AssetManager可以直接使用。 certified-assets canister 的上传 API 是@icp-sdk/canisters+upload_chunks,不是 SDK asset canister 的execute_operations/store/create_batch。commit_batch中的@icp-sdk/canisters/assets面向 legacy canister,不能用于 static-site。上传通过AssetManager时 recipe 的 sync plugin 完成;此 canister 没有可直接替代的 JavaScripticp deploy。(如果需要编程式上传,你几乎肯定应该使用 legacy canister——请参阅旧版参考。)AssetManager -
将/
_headers放在错误位置。 这两个文件必须位于_redirects的 根目录(例如dir)。它们会被当作配置读取,绝不会作为资源提供。请将它们放入dist/_redirects(Vite)或public/目录,使构建过程自动将其复制到static/;如果文件仍留在项目根目录且未被复制到dir,部署时便不会出现。dir -
在中设置保留标头。 sync plugin 会在部署时拒绝以下标头并给出说明性错误:
_headers、Content-Length、Content-Encoding、ETag、Transfer-Encoding、Accept-Ranges、Content-Range、IC-Certificate、IC-CertificateExpression。如需设置资源的媒体类型,请使用不带附加标头的Location形式(它会路由到资源元数据,而不是普通响应标头)。如需重定向,请使用Content-Type:——在_redirects中设置_headers标头不会产生重定向(状态仍为Location)。200 -
假设存在默认安全标头。 与 legacy canister 的不同,certified-assets canister 不会添加任何默认标头——没有
security_policy: "standard"、CSP 或Cache-Control。如需这些标头,请在X-Frame-Options中声明(见下方基线配置)。它自行管理的标头只有认证/服务相关标头及其_headerscookie。ic_env -
让/
404规则指向大型文件。 错误页面目标必须是 小型单块文件(约小于 1.9 MB)。大型文件会作为经过认证的410range response 提供,无法携带 4xx 状态,因此 plugin 会在部署时拒绝此类规则,并指出对应规则。(使用206rewrite 指向大型文件没有问题。)200 -
期待动态重定向捕获。 不支持或
:splat——无法转发捕获的路径段(:placeholder)。每个可认证响应都必须预先枚举,因此/old/:rest → /new/:rest/_redirects仅支持精确路径、末尾带_headers的子树通配符以及固定目标。/* -
将现有项目从 legacy asset canister 切换到 static-site。 仅将指向
recipe:并运行普通的@dfinity/static-site,会在安装任何内容 之前 失败:这是两个互不相关的 canister,其 Candid 接口也互不相关,因此 icp-cli 的预安装检查会中止并提示icp deploy。请改用Candid interface compatibility check failed: '<canister>' … You are making a BREAKING change。该命令会用 certified-assets canister 替换 wasm,丢弃旧的 stable memory——所有 legacy 资源、权限以及从icp deploy --mode reinstall派生的设置都会消失——并使 canister 处于空状态,随后 sync plugin 会从头上传整个.ic-assets.json5。将 static-site 作为全新 canister 部署可以完全避免此问题。不要用dir跳过检查;否则会尝试在 stable memory 上执行原地升级,而 certified-assets 无法读取该内存,最终留下一个无法提供任何内容的在线 canister。请参阅迁移参考。--yes -
以为 recipe 版本升级会自动重新安装自身。 在 certified-assets 自身的各版本之间升级比上述 legacy 切换更温和——Candid 接口在同一发布系列内保持稳定,因此不会阻止部署——但破坏性升级仍需你手动执行重新安装。canister 与 plugin 版本相互锁定,因此升级 recipe 后,会原地升级 canister,随后 sync plugin 会拒绝继续并报告
icp deploy,同时给出修复方式:对于 补丁 升级,运行assets canister version mismatch: canister is X, this plugin is Y(保留状态);对于 破坏性 升级(1.0 之前的 minor 版本、1.0 之后的 major 版本),运行icp canister install --mode upgrade,这会清除状态,使下一次 sync 重新上传所有资源和重定向规则。(icp canister install --mode reinstall→v0.3.x属于破坏性升级:先重新安装,再执行v0.4.0。icp deploy→v0.4.x属于补丁升级:先升级,再执行v0.4.3。)版本升级后 sync 失败属于预期行为,并非 bug。icp deploy -
会自动上传,无需额外配置。 plugin 会跳过 dotfile 和 dot-directory,但
.well-known/除外,它会正常遍历该目录。因此.well-known/无需任何额外设置即可在dir/.well-known/ic-domains提供服务。(这与 legacy canister 正好相反,后者需要通过/.well-known/ic-domains显式设置 un-ignore 规则。).ic-assets.json5 -
访问保护的启用顺序。 recipe 的会同时安装 canister 并同步资源,因此普通的“部署后再调用
icp deploy”流程会在短时间内公开提供内容。对于全新的 私有 应用,应在同步真实资源 之前 启用保护——先部署一个仅包含enable_protection的login.html,执行dir,然后再部署完整站点——这样资源在任何时候都不会被公众读取。登录页必须 完全自包含(内联 CSS/JS、enable_protectionURI)——它是唯一不受访问门禁保护的路径,而它引用的任何外部子资源本身也会受到门禁保护。请参阅访问保护。data: -
共享或链接URL。
raw.icp.net与<canister-id>.raw.icp.net提供的是同一站点,但 gateway 在转发响应时 不会检查证书,因此访问者获得的保障不会超过普通 Web 主机。与 legacy canister 的<canister-id>.icp.net不同,canister 没有拒绝allow_raw_access请求的设置:唯一的线索是未经认证的raw标头,而哪些主机名会进行验证属于 gateway 部署细节,并非协议的一部分。请链接到Host(或使用 verifying gateway 的自定义域名),并将https://<canister-id>.icp.net仅视为调试工具。启用访问保护后,使用rawURL 会非常危险:重定向和登录页都未经验证,因此不进行验证的 gateway 可能提供伪造的登录表单并窃取 token。访问 cookie 为 host-only,因此认证主机上的会话不会延续到raw。raw
SPA Routing and Redirects: _redirects
_redirectsSPA 路由与重定向:_redirects
_redirectsAdd a file to the root of your . Syntax follows Netlify's — one rule per line, three whitespace-separated fields (, , ); blank lines and comments are ignored.
_redirectsdir_redirectsfromtostatus#undefined在 的根目录添加 文件。语法遵循 Netlify 的 ——每行一条规则,由三个以空白分隔的字段组成(、、);空行和 注释会被忽略。
dir_redirects_redirectsfromtostatus#undefinedSingle-page-app fallback: serve the shell for any unmatched path (a rewrite, status 200)
Single-page-app fallback: serve the shell for any unmatched path (a rewrite, status 200)
/* /index.html 200
/* /index.html 200
Permanent redirect to a new internal path
Permanent redirect to a new internal path
/old-blog /blog 301
/old-blog /blog 301
Redirect to an external site
Redirect to an external site
/discord https://discord.gg/example 302
/discord https://discord.gg/example 302
Rewrite: serve /content/article.html at a pretty URL, no visible redirect
Rewrite: serve /content/article.html at a pretty URL, no visible redirect
/article /content/article.html 200
/article /content/article.html 200
Subtree redirect: everything under /docs/v1/ moves to /docs/v2/
Subtree redirect: everything under /docs/v1/ moves to /docs/v2/
/docs/v1/* /docs/v2/ 301
/docs/v1/* /docs/v2/ 301
Custom error pages (target must be a small single-chunk file)
Custom error pages (target must be a small single-chunk file)
/secret /403.html 404
/retired-feature /sunset.html 410
Status codes: `301`/`302`/`307`/`308` redirect; `200` is a **rewrite**; `404`/`410` serve an error page. `from` is always absolute and its only wildcard is a trailing `/*`. Precedence, first match wins: **real files** > automatic **clean-URL** rules > your `_redirects` (in file order) > the 404 fallback. Because a real file always wins, a `/*` SPA rule only catches paths nothing else claimed.
**SPA caveat — missing assets return HTML.** With `/* /index.html 200`, a typo'd `/assets/app-old.js` also matches `/*` and serves the shell as `text/html`. To give real 404s under a build-output folder, scope a narrower rule *above* the catch-all (rules match in file order):
/assets/* /404.html 404
/* /index.html 200
This needs a `404.html` in your `dir`; declaring `/*` means the built-in default 404 is not added./secret /403.html 404
/retired-feature /sunset.html 410
状态码:`301`/`302`/`307`/`308` 表示重定向;`200` 表示 **rewrite**;`404`/`410` 用于提供错误页面。`from` 始终为绝对路径,唯一支持的通配符是末尾的 `/*`。优先级按“首个匹配项胜出”计算:**真实文件** > 自动 **clean URL** 规则 > 你的 `_redirects`(按文件顺序)> 404 fallback。由于真实文件始终优先,因此 `/*` SPA 规则只会处理未被其他规则匹配的路径。
**SPA 注意事项——缺失的资源会返回 HTML。** 使用 `/* /index.html 200` 时,拼写错误的 `/assets/app-old.js` 也会匹配 `/*` 并以 `text/html` 返回 shell。若要让构建输出目录下的真实 404 生效,请在 catch-all 规则 **上方** 设置范围更窄的规则(规则按文件顺序匹配):
/assets/* /404.html 404
/* /index.html 200
这要求 `dir` 中存在 `404.html`;声明 `/*` 后,系统将不再添加内置的默认 404 页面。Custom Headers: _headers
_headers自定义标头:_headers
_headersAdd a file to the root of your . Syntax follows Netlify's : a path pattern on its own line, followed by indented lines; a blank line or ends a block. Patterns are absolute paths with an optional single wildcard (which matches too; there is no or ).
_headersdir_headersName: value#*/**?A useful baseline — act like a senior security engineer and tighten the CSP for your app:
/*
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'在 的根目录添加 文件。语法遵循 Netlify 的 :第一行是路径模式,随后是缩进的 行;空行或 会结束当前块。模式为绝对路径,可包含一个可选的 通配符(它也能匹配 ;不支持 或 )。
dir_headers_headersName: value#*/**?下面是一套实用的基线配置——应像资深安全工程师一样为应用收紧 CSP:
/*
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'Fingerprinted build assets never change — cache them hard
Fingerprinted build assets never change — cache them hard
/assets/*
Cache-Control: public, max-age=31536000, immutable
/assets/*
Cache-Control: public, max-age=31536000, immutable
HTML should revalidate so deploys are picked up
HTML should revalidate so deploys are picked up
/*.html
Cache-Control: public, max-age=0, must-revalidate
Key rules:
- **Patterns match the file (asset key), not the visitor's URL.** Write `/index.html`, not `/`. For a SPA, a `Cache-Control` on `/index.html` (or `/*.html`) is what every `/*`-rewritten client route gets; a block written against a route like `/dashboard/*` matches no file and does nothing.
- **All matching blocks contribute** — a file matching several blocks gets every block's headers (same-name values are combined comma-separated; `Set-Cookie` stays separate).
- **`Content-Type` is special** — the bare `Content-Type: <type>` form overrides the stored media type of the matching file (use it for extension-less files like `/llms.txt`); it is single-valued, first-match-wins, and is *not* emitted as an ordinary header.
- **`Set-Cookie` is allowed, but don't use the name `ic_env`.** The canister adds its own `ic_env` cookie to HTML responses as **two** `Set-Cookie` headers with the same name and value: one `SameSite=Lax`, one `SameSite=None; Partitioned` (so it survives in a cross-site iframe). Seeing two `ic_env` headers is expected, not a duplicate-header bug.
- Reserved headers are rejected at deploy time — see Pitfall 6./*.html
Cache-Control: public, max-age=0, must-revalidate
关键规则:
- **模式匹配的是文件(asset key),而不是访问者的 URL。** 应编写 `/index.html`,而不是 `/`。对于 SPA,在 `/index.html`(或 `/*.html`)上设置 `Cache-Control` 才能作用于所有经 `/*` rewrite 的客户端路由;针对 `/dashboard/*` 等路由编写的块不会匹配任何文件,因此不起作用。
- **所有匹配块都会生效**——一个文件匹配多个块时,会获得每个块中的所有标头(同名值以逗号连接;`Set-Cookie` 保持独立)。
- **`Content-Type` 特殊处理**——不带附加标头的 `Content-Type: <type>` 形式会覆盖匹配文件的已存储媒体类型(适用于 `/llms.txt` 等无扩展名文件);它是单值、首个匹配项胜出,并且 *不会* 作为普通标头发出。
- **允许使用 `Set-Cookie`,但不要使用名称 `ic_env`。** canister 会以 **两个** `Set-Cookie` 标头向 HTML 响应添加自己的 `ic_env` cookie,二者名称和值相同:一个使用 `SameSite=Lax`,另一个使用 `SameSite=None; Partitioned`(因此可在跨站 iframe 中保留)。看到两个 `ic_env` 标头属于预期现象,并非重复标头 bug。
- 保留标头会在部署时被拒绝——请参阅陷阱 6。Clean URLs and the 404 Page
Clean URL 与 404 页面
You don't link to files — the canister maps each HTML file to a clean, extension-less canonical URL and -redirects the other forms to it:
.html307| Your file | Canonical URL | Also handled (→ |
|---|---|---|
| | |
| | |
| | |
Requesting the underlying directly currently serves it (a file always beats a routing rule). For a custom 404, put a at the root of your ; otherwise a certified default is served. A SPA rule takes over the whole path space, so it replaces the default 404 with your shell.
/about.html200404.htmldir/*你无需直接链接 文件——canister 会将每个 HTML 文件映射到一个无扩展名的规范 URL,并通过 将其他形式重定向到该 URL:
.html307| 你的文件 | 规范 URL | 同样会处理(→ |
|---|---|---|
| | |
| | |
| | |
当前直接请求底层 会以 提供内容(真实文件始终优先于路由规则)。如需自定义 404 页面,请将 放在 的根目录;否则系统会提供经过认证的默认页面。SPA 的 规则会接管整个路径空间,因此会用你的 shell 替换默认 404 页面。
/about.html200404.htmldir/*Custom Domains
自定义域名
To serve from your own domain, add a file to your , one domain per line:
.well-known/ic-domainsdirexample.com
www.example.com.well-known/custom-domains如需通过自有域名提供内容,请在 中添加 文件,每行写入一个域名:
dir.well-known/ic-domainsexample.com
www.example.com.well-known/custom-domainsAccess Protection (private apps)
访问保护(私有应用)
Put a login gate in front of an in-progress or preview app. Unauthenticated visitors get a certified (HTML) or (other assets). Configure it through controller-only canister methods:
307 → <login_page>401sh
undefined可以在开发中或预览应用前放置登录门禁。未通过认证的访问者会收到经过认证的 (HTML),或针对其他资源收到 。请通过仅限 controller 调用的 canister 方法进行配置:
307 → <login_page>401sh
undefined1. Add a self-contained /login.html to your dir and deploy.
1. Add a self-contained /login.html to your dir and deploy.
icp deploy
icp deploy
2. Turn the gate on, naming your login page.
2. Turn the gate on, naming your login page.
icp canister call frontend enable_protection '("/login.html")'
icp canister call frontend enable_protection '("/login.html")'
3. Mint a credential (here: a chosen passphrase valid ~1 year). Pass value = null for a random token.
3. Mint a credential (here: a chosen passphrase valid ~1 year). Pass value = null for a random token.
issue_token takes a record (IssueTokenArgs), not positional args.
issue_token takes a record (IssueTokenArgs), not positional args.
icp canister call frontend issue_token '(record { label = "owner"; ttl_secs = 31536000 : nat32; value = opt "my-passphrase" })'
> **Ordering & the public window.** The `static-site` recipe's `icp deploy` **installs the canister and syncs your assets in one step**, so the sequence above serves your content publicly for the brief window between that first deploy and `enable_protection` — fine when gating an existing or preview app. To avoid *any* public exposure for a **brand-new private app**, enable protection **before your real assets are synced**: run the first `icp deploy` with a `dir` containing only `login.html`, then `enable_protection '("/login.html")'`, then `icp deploy` again with the full site. The login page is gate-exempt, so nothing private is ever served unauthenticated (Pitfall 13). (Enabling on a truly empty canister also works — the canister reports `EnabledLoginPageMissing` and self-heals to `Enabled` once `login.html` is synced.)
| Method | Effect |
|--------|--------|
| `issue_token '(record { label = "<label>"; ttl_secs = <secs> : nat32; value = opt "<value>" })'` | Mints a token, returns its value. `value = null` → high-entropy random token. |
| `revoke_token '("<label>")'` | Removes every token with that label, live. |
| `list_tokens '()'` | Live tokens `{ label; expires_at }` (controller-only). |
| `check_protection_status '()'` | `Disabled`, `Enabled`, or `EnabledLoginPageMissing`. |
| `disable_protection '()'` | Gate off, drops all tokens. |
Always pass the argument explicitly — `'()'` for the methods that take none. Called with no argument, `icp canister call` opens an interactive prompt instead of sending an empty one.
This is **access gating, not confidentiality**: node operators can read asset bytes and the token store, there is no rate-limiting, and it relies on the honest-replica/honest-gateway assumption. The gate runs canister-side on every hostname, but its redirect and login page are only verified through a verifying gateway, so never send people to a `raw` URL of a protected app (Pitfall 14). Use high-entropy random tokens for share links; enable *before* the first sync for a new private app (Pitfall 13). Full details in the [certified-assets access-protection docs](https://github.com/dfinity/certified-assets/blob/v0.4.3/docs/access-protection.md).icp canister call frontend issue_token '(record { label = "owner"; ttl_secs = 31536000 : nat32; value = opt "my-passphrase" })'
> **顺序与公开窗口。** `static-site` recipe 的 `icp deploy` 会在一个步骤中 **安装 canister 并同步资源**,因此上述顺序会在首次部署与 `enable_protection` 之间的短暂窗口内公开提供内容——对于已有应用或预览应用通常没有问题。若要确保全新的 **私有应用** 绝不出现公开暴露,应在同步真实资源 **之前** 启用保护:首次 `icp deploy` 时让 `dir` 仅包含 `login.html`,然后执行 `enable_protection '("/login.html")'`,最后使用完整站点再次执行 `icp deploy`。登录页不受门禁限制,因此任何私有内容都不会在未经认证的情况下提供(陷阱 13)。(在完全为空的 canister 上启用保护同样可行——canister 会报告 `EnabledLoginPageMissing`,并在同步 `login.html` 后自动恢复为 `Enabled`。)
| 方法 | 效果 |
|--------|--------|
| `issue_token '(record { label = "<label>"; ttl_secs = <secs> : nat32; value = opt "<value>" })'` | 创建一个 token 并返回其值。`value = null` → 生成高熵随机 token。 |
| `revoke_token '("<label>")'` | 立即删除具有该标签的所有 token。 |
| `list_tokens '()'` | 获取当前有效的 token `{ label; expires_at }`(仅限 controller)。 |
| `check_protection_status '()'` | 返回 `Disabled`、`Enabled` 或 `EnabledLoginPageMissing`。 |
| `disable_protection '()'` | 关闭门禁并删除所有 token。 |
始终显式传入参数——对于不需要参数的方法,传入 `'()'`。如果不带参数调用,`icp canister call` 会打开交互式提示,而不会发送空参数。
这是 **访问门禁,而非保密机制**:节点运营者可以读取资源字节和 token 存储,系统没有速率限制,并且依赖 honest-replica/honest-gateway 假设。门禁在 canister 端对每个主机名运行,但其重定向和登录页只有通过 verifying gateway 时才会得到验证,因此绝不要将用户引导至受保护应用的 `raw` URL(陷阱 14)。如需创建分享链接,请使用高熵随机 token;对于新的私有应用,应在首次 sync 之前启用保护(陷阱 13)。完整详情请参阅 [certified-assets 访问保护文档](https://github.com/dfinity/certified-assets/blob/v0.4.3/docs/access-protection.md)。Authorizing Uploaders
授权上传者
Uploads (sync) are performed by canister controllers and by a separate set of authorized syncer principals. To let a CI/deploy principal sync without giving it full canister control, it — do not , which grants upgrade/settings/delete power far beyond uploading.
authorize--add-controllerbash
undefined上传(sync)由 canister controllers 和一组独立的 authorized syncer principals 执行。若希望 CI/deploy principal 具备同步权限,而无需授予其完整的 canister 控制权,应使用 进行授权——不要使用 ,因为后者会授予升级、设置和删除等远超上传所需的权限。
authorize--add-controllerbash
undefinedAllow a principal to sync assets (upload), without making it a controller
Allow a principal to sync assets (upload), without making it a controller
icp canister call frontend authorize '(principal "<principal-id>")'
icp canister call frontend authorize '(principal "<principal-id>")'
List authorized syncers
List authorized syncers
icp canister call frontend list_authorized '()'
icp canister call frontend list_authorized '()'
Revoke
Revoke
icp canister call frontend deauthorize '(principal "<principal-id>")'
> **Security Warning:** `icp canister settings update frontend --add-controller <principal-id>` grants full canister control (upgrade wasm, change settings, delete, drain cycles) — not just upload access. Prefer `authorize` for deploy pipelines.icp canister call frontend deauthorize '(principal "<principal-id>")'
> **安全警告:** `icp canister settings update frontend --add-controller <principal-id>` 会授予完整的 canister 控制权(升级 wasm、修改设置、删除、消耗 cycles),而不仅仅是上传权限。对于部署流水线,应优先使用 `authorize`。Building Against Canister IDs (presync
vs build
)
presyncbuild基于 Canister ID 构建(presync
与 build
)
presyncbuildbuildpresyncyaml
canisters:
- name: frontend
recipe:
type: "@dfinity/static-site@v0.4.3"
configuration:
dir: dist
presync:
- npm ci
# $ICP_CLI_CID_BACKEND is the `backend` canister's principal.
- VITE_CANISTER_ID_BACKEND=$ICP_CLI_CID_BACKEND npm run buildVariables available to : (this canister), (each project canister — name upper-cased, non-alphanumerics → , e.g. → ), , .
presyncICP_CLI_CIDICP_CLI_CID_<NAME>_backendICP_CLI_CID_BACKENDICP_CLI_NETWORKICP_CLI_ENVIRONMENTAlternatively, read canister IDs at runtime in the browser from the cookie the canister sets on every HTML response (works both locally and on mainnet with no environment branching) — see the and skills for the pattern. Prefer the cookie over .
ic_envuser-sign-inicp-clisafeGetCanisterEnv()fetchRootKey()buildpresyncyaml
canisters:
- name: frontend
recipe:
type: "@dfinity/static-site@v0.4.3"
configuration:
dir: dist
presync:
- npm ci
# $ICP_CLI_CID_BACKEND is the `backend` canister's principal.
- VITE_CANISTER_ID_BACKEND=$ICP_CLI_CID_BACKEND npm run buildpresyncICP_CLI_CIDICP_CLI_CID_<NAME>_backendICP_CLI_CID_BACKENDICP_CLI_NETWORKICP_CLI_ENVIRONMENT另一种方式是在浏览器中于 运行时 从 canister 为每个 HTML 响应设置的 cookie 读取 canister ID(本地和主网均适用,无需判断环境)——请参阅 和 skill,了解 模式。应优先使用 cookie,而不是 。
ic_envuser-sign-inicp-clisafeGetCanisterEnv()fetchRootKey()What You Get Automatically
自动获得的功能
No configuration needed — on by default:
- Response certification — every response is certified; a verifying gateway (not ) checks the proof.
raw - Clean URLs — canonicalization (above).
307 - Compression — compressible assets are stored gzip + Brotli alongside the original and negotiated per request via . Compressible means: any
Accept-Encoding; anytext/*or+jsonsuffix (so+xml,image/svg+xml);application/xhtml+xml,application/javascript,application/json,application/xml; andapplication/wasmexceptfont/*/woff(already compressed). An encoding is kept only if it actually came out smaller than the original.woff2 - ETag / — content-hash ETag; unchanged files aren't re-downloaded.
304 Not Modified - A default certified — replaceable with your own
404./404.html - The cookie — on HTML responses (as two
ic_envheaders,Set-CookieandLax), carryingNone; Partitionedenv vars (canister IDs) and the root key for the frontend.PUBLIC_*
无需任何配置,以下功能默认启用:
- Response certification——每个响应都会经过认证;verifying gateway(而不是 )会检查证明。
raw - Clean URL——执行 规范化(见上文)。
307 - 压缩——可压缩资源会以 gzip + Brotli 形式与原文件一并存储,并根据每次请求的 进行协商。可压缩内容包括:任意
Accept-Encoding;任意以text/*或+json结尾的类型(因此包括+xml、image/svg+xml);application/xhtml+xml、application/javascript、application/json、application/xml;以及除application/wasm/woff(已压缩)之外的woff2。只有当编码后的结果确实小于原文件时,才会保留该编码。font/* - ETag / ——使用内容哈希 ETag;未变化的文件不会重复下载。
304 Not Modified - 默认的经过认证的 ——可替换为你自己的
404。/404.html - cookie——添加到 HTML 响应中(以两个
ic_env标头发出,分别为Set-Cookie和Lax),其中携带None; Partitioned环境变量(canister ID)以及前端的 root key。PUBLIC_*
Deploy & Verify
部署与验证
bash
undefinedbash
undefinedStart the local network
Start the local network
icp network start -d
icp network start -d
Build + deploy everything (or just the frontend)
Build + deploy everything (or just the frontend)
icp deploy
icp deploy frontend
icp deploy
icp deploy frontend
Mainnet (needs cycles)
Mainnet (needs cycles)
icp deploy -e ic frontend
Re-running `icp deploy` re-syncs: the plugin diffs your directory against the canister and uploads only what changed.
```bashicp deploy -e ic frontend
再次运行 `icp deploy` 会重新同步:plugin 会比较你的目录与 canister,仅上传发生变化的资源。
```bashCanister is running
Canister is running
icp canister status frontend # Status: Running, non-zero memory
icp canister status frontend # Status: Running, non-zero memory
Get the canister ID (there is no icp canister id
; use status --id-only)
icp canister idGet the canister ID (there is no icp canister id
; use status --id-only)
icp canister idicp canister status frontend --id-only
icp canister status frontend --id-only
Fetch the index page (certified)
Fetch the index page (certified)
icp canister call frontend http_request '(record {
url = "/"; method = "GET"; body = vec {}; headers = vec {};
certificate_version = opt 2;
})' # → status_code = 200
icp canister call frontend http_request '(record {
url = "/"; method = "GET"; body = vec {}; headers = vec {};
certificate_version = opt 2;
})' # → status_code = 200
SPA fallback returns the shell, not 404
SPA fallback returns the shell, not 404
icp canister call frontend http_request '(record {
url = "/dashboard/settings"; method = "GET"; body = vec {}; headers = vec {};
certificate_version = opt 2;
})' # → 200 (index.html), NOT 404
icp canister call frontend http_request '(record {
url = "/dashboard/settings"; method = "GET"; body = vec {}; headers = vec {};
certificate_version = opt 2;
})' # → 200 (index.html), NOT 404
Open in a browser (this is the URL icp deploy
prints)
icp deployOpen in a browser (this is the URL icp deploy
prints)
icp deployMainnet: https://<frontend-canister-id>.icp.net
Mainnet: https://<frontend-canister-id>.icp.net
undefinedundefinedVerifying Deployed Contents (state hash)
验证已部署内容(state hash)
Certification proves responses match what the canister committed to; the state hash proves what it committed to matches a build reproduced from public source. The hash prints () comes from the canister itself — a deploy self-consistency check, not third-party verification. To verify a canister:
icp deploycanister reports state hash <hex>bash
undefinedCertification 证明响应与 canister 已提交的内容一致;state hash 则证明 canister 提交的内容 与根据公开源代码复现出的构建结果一致。 输出的哈希()来自 canister 本身——这是部署期间的自一致性检查,不是第三方验证。如需验证 canister:
icp deploycanister reports state hash <hex>bash
undefined1. Reproduce the build from source at the deployed version → ./dist (incl. _headers/_redirects)
1. Reproduce the build from source at the deployed version → ./dist (incl. _headers/_redirects)
2. Ask the canister its release, then build the verifier from THAT tag.
2. Ask the canister its release, then build the verifier from THAT tag.
Not published as a binary or on crates.io. --locked is required: Cargo.lock pins the
Not published as a binary or on crates.io. --locked is required: Cargo.lock pins the
compressor builds whose output bytes the hash covers; without it the hash differs.
compressor builds whose output bytes the hash covers; without it the hash differs.
icp canister call <canister-id> version '()' -n ic --query
icp canister call <canister-id> version '()' -n ic --query
(record { major = 0 : nat32; minor = 4 : nat32; patch = 3 : nat32 })
(record { major = 0 : nat32; minor = 4 : nat32; patch = 3 : nat32 })
cargo install --git https://github.com/dfinity/certified-assets --tag v0.4.3 --locked state-hash-cli
cargo install --git https://github.com/dfinity/certified-assets --tag v0.4.3 --locked state-hash-cli
3. Compute the hash locally (prints 64 hex chars)
3. Compute the hash locally (prints 64 hex chars)
state-hash ./dist
state-hash ./dist
4. Read the canister's hash (an update call, so consensus-backed); the hash is the last 32 bytes
4. Read the canister's hash (an update call, so consensus-backed); the hash is the last 32 bytes
icp canister call <canister-id> state_hash '()' -n ic -o hex | tail -c 65
- Target the canister by **principal** with `-n <network>`; `-e <environment>` resolves a canister *name* from a local project, which a third-party verifier doesn't have. Pass `'()'` explicitly.
- **32 zero bytes is not a hash**: the canister has never finished a sync, or one is in progress (a sync drops the cached hash when it starts). Re-read after the deploy completes.
- A mismatch means content, headers, or redirects differ from the source — or the canister was prepared with non-standard compressors (platforms embedding the crates may do this; the tool only reproduces what `icp deploy` does).
- **Not covered by the hash:** the `ic_env` cookie (a controller can repoint a frontend's backend canister ID via env vars with a byte-identical build) and access protection (a matching hash says the canister holds your build, not that a visitor can reach it).icp canister call <canister-id> state_hash '()' -n ic -o hex | tail -c 65
- 使用 `-n <network>` 通过 **principal** 定位 canister;`-e <environment>` 会从本地项目中解析 canister *名称*,而第三方验证者没有这些名称。请显式传入 `'()'`。
- **32 个零字节不是哈希**:说明 canister 从未完成 sync,或 sync 正在进行(sync 开始时会清除缓存的哈希)。请在部署完成后重新读取。
- 哈希不匹配意味着内容、标头或重定向与源代码存在差异——或者 canister 使用非标准 compressor 进行了准备(嵌入这些 crate 的平台可能会这样做;该工具只会复现 `icp deploy` 的行为)。
- **哈希不涵盖以下内容:** `ic_env` cookie(controller 可以通过环境变量重新指向前端后端 canister 的 ID,同时保持构建结果逐字节相同)以及访问保护(匹配的哈希表示 canister 持有你的构建结果,并不表示访问者一定能够访问它)。Legacy Asset Canister and Migration
Legacy Asset Canister 与迁移
- Maintaining an existing project (
@dfinity/asset-canister,.ic-assets.json5uploads,AssetManagerroles,grant_permission): seeallow_raw_access.references/legacy-asset-canister.md - Moving an existing asset-canister project to certified-assets / static-site: see for the config mapping and the reinstall-mode caveat.
references/migrating-from-asset-canister.md
- 维护现有 项目(
@dfinity/asset-canister、.ic-assets.json5上传、AssetManager角色、grant_permission):请参阅allow_raw_access。references/legacy-asset-canister.md - 将现有 asset-canister 项目迁移到 certified-assets / static-site:有关配置映射和 reinstall-mode 注意事项,请参阅 。
references/migrating-from-asset-canister.md
Additional References
其他参考
- Load for the recipe system,
icp-clistructure, canister-ID injection, and theicp.yamlcookie /ic_envpattern.safeGetCanisterEnv() - Load for DNS records, ACME challenge, and TLS provisioning of a custom domain.
custom-domains - Load for reading the root key and canister IDs from
user-sign-inin a frontend.ic_env - Full upstream user docs: certified-assets docs.
- 加载 ,了解 recipe 系统、
icp-cli结构、canister ID 注入以及icp.yamlcookie /ic_env模式。safeGetCanisterEnv() - 加载 ,了解自定义域名的 DNS 记录、ACME challenge 和 TLS 配置。
custom-domains - 加载 ,了解如何在前端从
user-sign-in读取 root key 和 canister ID。ic_env - 完整的上游用户文档:certified-assets docs。