Foldkit이란? Effect 기반 타입스크립트 프론트엔드 시작하기
프론트엔드에서 버튼 클릭, API 응답, 화면 상태가 많아지면 어떤 사건이 현재 화면을 만들었는지 추적하기 어려워집니다. Foldkit 공식 웹사이트에서 소개하는 Foldkit은 Effect를 바탕으로 상태 변경과 비동기 작업의 흐름을 명시하는 TypeScript 프론트엔드 프레임워크입니다.[1]
이 글에서는 Foldkit의 구조를 살펴보고, 공식 스캐폴더로 카운터 앱을 만들어 테스트합니다. Effect가 처음이라면 이전 글 Effect란? 타입스크립트에서 비동기 작업과 오류를 다루는 방법을 먼저 읽어도 좋습니다.
Foldkit은 무엇인가요?
Foldkit은 Effect 공식 웹사이트의 라이브러리와 The Elm Architecture를 바탕으로 동작합니다. 앱의 상태를 Model로 표현하고, 사건을 Message로 전달해 update에서 다음 상태를 결정합니다. view는 상태를 화면으로 표현합니다.[2][6]
버튼 클릭을 예로 들면 흐름은 다음과 같습니다.
Click → Message → update → Model → view → UI
일회성 API 호출이나 지연 같은 부수 효과가 필요하면 update가 작업을 직접 실행하지 않고 Command를 반환합니다. 런타임이 작업을 실행하고 결과를 다시 Message로 전달합니다.[6][8] Effect 자체가 프론트엔드 프레임워크인 것은 아닙니다. Foldkit이 Effect 위에 UI 애플리케이션 구조를 제공합니다.
설치 전 확인할 점
Foldkit은 MIT 라이선스의 오픈소스이며, 아직 1.0 이전 버전입니다. 프로젝트는 마이너 버전에서도 호환성이 깨질 수 있다고 안내합니다.[2][3] 도입할 때는 잠금 파일을 유지하고 의존성을 함께 확인하세요.
공식 시작 가이드는 Node.js 22.22.2 이상을 안내합니다.[5] 아래 실습은 Node.js 26, create-foldkit-app 0.41.0으로 실행했습니다. 생성된 프로젝트의 foldkit과 @foldkit/ui는 0.170.0, effect는 4.1.0이었습니다. 같은 시점 npm의 foldkit 최신 버전은 0.171.0이었으므로 스캐폴더 버전과 생성된 프레임워크 버전을 혼동하지 마세요.[10][11] 향후 생성되는 버전과 API는 달라질 수 있습니다.
카운터 앱 만들기
새 작업 디렉터리에서 다음 명령을 실행합니다. --example counter는 브라우저 전용 카운터 예제를 선택하고, 스캐폴더가 의존성을 설치합니다.[5][11]
npx --yes create-foldkit-app@0.41.0 --name foldkit-counter --rendering spa --example counter --package-manager npm
cd foldkit-counter
npm run dev
터미널에 표시되는 로컬 주소를 브라우저에서 열면 숫자와 -, Reset, + 버튼이 나타납니다. +를 누르면 값이 증가하고 Reset은 초기값으로 되돌립니다. 생성한 프로젝트를 직접 실행하고 +를 두 번 눌러 숫자 2가 표시되는 것을 확인했습니다.

공식 Counter 스타터를 로컬에서 실행한 화면. +를 두 번 눌렀을 때의 상태입니다. (출처: Foldkit Counter 예제, 2026-11-20 캡처)
다른 터미널에서 실행하거나 개발 서버를 종료한 뒤, 아래 명령으로 타입 검사, 테스트와 배포용 빌드를 확인합니다.
npm run typecheck
npm test
npm run build
검증 환경에서 타입 검사와 빌드가 성공했고, 제공된 테스트 10개가 모두 통과했습니다. 이 결과는 해당 시점에 설치된 의존성과 환경에 대한 확인이며, 모든 환경에서 동일한 결과를 보장하지는 않습니다.
Model과 Message는 어디에 있나요?
카운터 스타터에서 src/main.ts는 Model, Message, update, init, view를 정의하고, src/entry.ts는 이를 가져와 런타임을 시작합니다.[5] 다음은 생성된 src/main.ts의 상태와 업데이트 부분을 발췌한 것입니다. 파일 전체가 아니므로 기존 파일을 이 코드로 덮어쓰지는 마세요.
import { Schema } from 'effect'
import { Runtime, type Update } from 'foldkit'
import { Document, HtmlBuilder } from 'foldkit/html'
import { defineMessageUnion } from 'foldkit/message'
import { modifyFields } from 'foldkit/struct'
import { Button } from '@foldkit/ui'
// MODEL
export const Model = Schema.Struct({ count: Schema.Number })
export type Model = typeof Model.Type
// MESSAGE
export const Message = defineMessageUnion({
ClickedDecrement: {},
ClickedIncrement: {},
ClickedReset: {},
})
export type Message = typeof Message.Type
// UPDATE
export const update = (model: Model, message: Message) =>
Message.match<Update.Return<Model, Message>>(message, {
ClickedDecrement: () => ({
model: modifyFields(model, { count: count => count - 1 }),
}),
ClickedIncrement: () => ({
model: modifyFields(model, { count: count => count + 1 }),
}),
ClickedReset: () => ({ model: modifyFields(model, { count: () => 0 }) }),
})
Model은 숫자 상태를 정의하고, Message는 세 가지 버튼 사건을 선언합니다. update는 사건에 따라 새 모델을 반환하며, 같은 파일의 view가 버튼과 값을 렌더링합니다. 초깃값은 init에 있고 실행 연결은 entry.ts에 있습니다. 제공된 src/story.test.ts와 src/scene.test.ts도 열어 상태 전이와 사용자 상호작용 테스트를 비교해 보세요.
실제 프로젝트에 어떻게 활용할 수 있나요?
- 다단계 폼: 입력, 검증 중, 성공, 실패를 모델과 메시지로 나누면 상태 변화의 위치를 찾기 쉽습니다.
- API 연동: 요청을
Command로 표현하고 성공·실패 결과를 메시지로 받아 화면 상태를 갱신할 수 있습니다.[6][8] - 실시간 화면: 외부 이벤트의
Subscription과 연결 수명을 다루는ManagedResource를 활용할 수 있습니다.[6] - UI 구성: 별도 패키지
@foldkit/ui는 Dialog, Menu 등 상태를 가진 Submodel과 Button 같은 상태 없는 헬퍼를 제공합니다. 마크업과 스타일은 개발자가 지정합니다.[4] - 디버깅과 AI: DevTools에서 상태와 메시지 기록을 살펴볼 수 있고, 별도의 MCP 서버를 통해 에이전트가 런타임 데이터에 접근할 수 있습니다.[1][9]
AI 도구를 연결할 때는 Model, 메시지 기록, Command 인자에 민감 정보가 들어가지 않도록 주의하세요. 공식 문서는 DevTools MCP를 권한이 높은 접근으로 취급하며, 고정 포트를 사용할 경우 인증 없이 수신하므로 신뢰할 수 없는 네트워크에서 사용하지 말라고 안내합니다.[9] 실제 토큰 대신 테스트 데이터를 사용하세요.
도입 전 확인: 학습 비용과 보안
Foldkit은 상태 흐름을 한 방식으로 정리하고 싶은 앱에 적합할 수 있습니다. 반면 작은 정적 사이트나 기존 React 생태계에 깊이 의존하는 앱에서는 전환 비용이 이점보다 클 수 있습니다. Effect, Schema, 메시지 기반 상태 전이를 팀이 배워야 한다는 점도 고려해야 합니다.[1] 기존 앱 전체를 바꾸기 전에 작은 위젯이나 독립 화면으로 검증하는 편이 안전합니다.
의존성 검사 결과: 2026-11-20에 위 스캐폴더로 설치한 뒤 npm audit은 취약점 6건(보통 1, 높음 3, 심각 2)을 보고했습니다. 이는 해당 설치의 개발·전이 의존성을 포함한 결과이며, Foldkit 핵심 패키지 자체가 모두 취약하다는 뜻이나 앱이 실제 악용됐다는 뜻은 아닙니다. 결과는 시간이 지나거나 버전이 달라지면 바뀝니다. 프로젝트에서 npm audit의 패키지·영향 범위·수정 버전을 확인하고, 자동 수정이나 강제 업그레이드는 호환성 검토와 테스트 후 적용하세요.
Sources
[3] https://github.com/foldkit/foldkit
[4] https://foldkit.dev/ui/overview
[5] https://foldkit.dev/get-started
[6] https://foldkit.dev/core/architecture
[8] https://foldkit.dev/core/commands
[9] https://foldkit.dev/ai/mcp
When clicks, API responses, and screen states multiply, it can be hard to trace how a screen reached its current state. Foldkit is a TypeScript frontend framework built on Effect that makes state transitions and asynchronous work explicit.[1]
This guide explains the architecture and creates and tests a counter with the official scaffolder. If Effect is new to you, see our earlier Effect introduction.
What is Foldkit?
Foldkit builds on Effect and The Elm Architecture. It describes application state as a Model, passes events as Message values, decides the next state in update, and renders the state through view.[2][6]
A button click follows this flow:
Click → Message → update → Model → view → UI
For a one-time side effect such as an API request or delay, update returns a Command rather than running the work itself. The runtime executes the work and sends the result back as a Message.[6][8] Effect itself is not a frontend framework; Foldkit supplies the UI application architecture on top of Effect.
Before installing
Foldkit is MIT-licensed open source and is still pre-1.0. The project warns that minor versions may introduce breaking changes.[2][3] Keep your lockfile and review dependencies when adopting it.
The official guide requires Node.js 22.22.2 or newer.[5] We tested with Node.js 26 and create-foldkit-app 0.41.0. The generated project installed foldkit and @foldkit/ui 0.170.0, and effect 4.1.0. The npm latest foldkit was 0.171.0 at the same time: the scaffolder version and generated framework version are different things.[10][11] Future versions and APIs may change.
Create a counter app
Run the following in a new working directory. --example counter chooses the browser-only counter; the scaffolder installs the dependencies.[5][11]
npx --yes create-foldkit-app@0.41.0 --name foldkit-counter --rendering spa --example counter --package-manager npm
cd foldkit-counter
npm run dev
Open the local address shown in the terminal. The screen has a number and -, Reset, and + buttons. + increases the value and Reset returns it to the initial value. We ran the generated project and confirmed that two clicks on + displayed 2.

The official Counter starter running locally after two clicks on +. (Source: Foldkit Counter example, captured 2026-11-20)
Run type checks, tests, and a production build in another terminal or after stopping the dev server:
npm run typecheck
npm test
npm run build
In our environment, type checking and the build succeeded and all 10 provided tests passed. This confirms the installed dependencies and environment at that time, not every possible environment.
Where are Model and Message?
In the counter starter, src/main.ts defines Model, Message, update, init, and view; src/entry.ts imports them and starts the runtime.[5] The following is an excerpt of the generated src/main.ts, not the complete file. Do not replace the whole file with it.
import { Schema } from 'effect'
import { Runtime, type Update } from 'foldkit'
import { Document, HtmlBuilder } from 'foldkit/html'
import { defineMessageUnion } from 'foldkit/message'
import { modifyFields } from 'foldkit/struct'
import { Button } from '@foldkit/ui'
// MODEL
export const Model = Schema.Struct({ count: Schema.Number })
export type Model = typeof Model.Type
// MESSAGE
export const Message = defineMessageUnion({
ClickedDecrement: {},
ClickedIncrement: {},
ClickedReset: {},
})
export type Message = typeof Message.Type
// UPDATE
export const update = (model: Model, message: Message) =>
Message.match<Update.Return<Model, Message>>(message, {
ClickedDecrement: () => ({
model: modifyFields(model, { count: count => count - 1 }),
}),
ClickedIncrement: () => ({
model: modifyFields(model, { count: count => count + 1 }),
}),
ClickedReset: () => ({ model: modifyFields(model, { count: () => 0 }) }),
})
Model defines the numeric state, Message declares the three button events, and update returns the next model. The view in the same file renders the buttons and value. init sets the initial value and entry.ts connects the runtime. Open src/story.test.ts and src/scene.test.ts to compare state-transition and interaction tests.
How can you use it?
- Multi-step forms: model input, validation, success, and failure as states and messages.
- API integration: describe a request as a
Commandand update the screen with success or failure messages.[6][8] - Real-time interfaces: use
Subscriptionfor external events andManagedResourcefor the lifetime of a connection.[6] - UI composition: the separate
@foldkit/uipackage includes stateful Submodels such as Dialog and Menu and stateless helpers such as Button. You provide markup and styling.[4] - Debugging and AI: DevTools shows state and message history; a separate MCP server can expose runtime data to an agent.[1][9]
Keep sensitive information out of Models, message history, and Command arguments when connecting AI tools. The documentation treats DevTools MCP as privileged access and warns that a fixed port listens without authentication; do not use it on untrusted networks.[9] Use test data rather than real tokens.
Before adopting: learning and security
Foldkit may fit apps that benefit from a shared state-flow convention. For a small static site or an application deeply invested in React, migration costs may outweigh the benefits. The team must also learn Effect, Schema, and message-based transitions.[1] Evaluate a small widget or independent screen before a wider migration.
Dependency audit: On 2026-11-20, npm audit on the installation above reported 6 vulnerabilities (1 moderate, 3 high, 2 critical). This includes development and transitive dependencies; it does not mean all issues are in Foldkit's core package or that the app was exploited. Results change with time and versions. Review affected packages, exposure, and fixed versions in npm audit; test compatibility before automatic fixes or forced upgrades.
Sources
[3] https://github.com/foldkit/foldkit
[4] https://foldkit.dev/ui/overview
[5] https://foldkit.dev/get-started
[6] https://foldkit.dev/core/architecture
[8] https://foldkit.dev/core/commands
[9] https://foldkit.dev/ai/mcp
当点击、API 响应和页面状态不断增加时,要追踪页面如何到达当前状态可能并不容易。Foldkit 官网介绍的 Foldkit 是基于 Effect 的 TypeScript 前端框架,用于明确表达状态变化和异步操作。[1]
本文介绍其架构,并使用官方脚手架创建和测试计数器。如果你还不熟悉 Effect,可以先阅读我们的 Effect 入门文章。
什么是 Foldkit?
Foldkit 基于 Effect 和 The Elm Architecture。它用 Model 表示应用状态,用 Message 传递事件,由 update 决定下一个状态,再由 view 渲染界面。[2][6]
按钮点击的流程如下:
Click → Message → update → Model → view → UI
对于 API 请求或延迟等一次性副作用,update 返回 Command,而不是自行执行。运行时执行操作,并以 Message 返回结果。[6][8] Effect 本身不是前端框架;Foldkit 在 Effect 之上提供 UI 应用架构。
安装前的准备
Foldkit 是 MIT 许可的开源项目,目前尚未达到 1.0。项目提醒,次版本也可能引入破坏性变更。[2][3] 使用时请保留锁文件并检查依赖。
官方指南要求 Node.js 22.22.2 或更新版本。[5] 本文使用 Node.js 26 和 create-foldkit-app 0.41.0 验证。生成项目中的 foldkit 和 @foldkit/ui 为 0.170.0,effect 为 4.1.0。同一时间 npm 最新 foldkit 为 0.171.0,脚手架版本与生成的框架版本并不相同。[10][11] 后续版本和 API 可能改变。
创建计数器应用
在新的工作目录运行以下命令。--example counter 选择仅在浏览器中运行的计数器,脚手架会安装依赖。[5][11]
npx --yes create-foldkit-app@0.41.0 --name foldkit-counter --rendering spa --example counter --package-manager npm
cd foldkit-counter
npm run dev
在浏览器中打开终端显示的本地地址,即可看到数字和 -、Reset、+ 按钮。+ 增加数值,Reset 恢复初始值。我们运行生成的项目并确认点击两次 + 后显示 2。

本地运行官方 Counter 初始项目,点击两次 + 后的状态。(来源:Foldkit Counter 示例,截取于 2026-11-20)
在另一个终端,或停止开发服务器后,执行类型检查、测试和构建:
npm run typecheck
npm test
npm run build
在验证环境中,类型检查与构建成功,附带的 10 项测试全部通过。结果只适用于当时安装的依赖与环境,不保证所有环境相同。
Model 和 Message 在哪里?
Counter 初始项目的 src/main.ts 定义 Model、Message、update、init 和 view;src/entry.ts 导入它们并启动运行时。[5] 以下只是生成的 src/main.ts 片段,不是完整文件,请勿用它覆盖整个文件。
import { Schema } from 'effect'
import { Runtime, type Update } from 'foldkit'
import { Document, HtmlBuilder } from 'foldkit/html'
import { defineMessageUnion } from 'foldkit/message'
import { modifyFields } from 'foldkit/struct'
import { Button } from '@foldkit/ui'
// MODEL
export const Model = Schema.Struct({ count: Schema.Number })
export type Model = typeof Model.Type
// MESSAGE
export const Message = defineMessageUnion({
ClickedDecrement: {},
ClickedIncrement: {},
ClickedReset: {},
})
export type Message = typeof Message.Type
// UPDATE
export const update = (model: Model, message: Message) =>
Message.match<Update.Return<Model, Message>>(message, {
ClickedDecrement: () => ({
model: modifyFields(model, { count: count => count - 1 }),
}),
ClickedIncrement: () => ({
model: modifyFields(model, { count: count => count + 1 }),
}),
ClickedReset: () => ({ model: modifyFields(model, { count: () => 0 }) }),
})
Model 定义数值状态,Message 声明三个按钮事件,update 返回下一个模型。同一文件中的 view 渲染按钮和数值;init 提供初始值,entry.ts 连接运行时。可以查看 src/story.test.ts 和 src/scene.test.ts,比较状态转换测试与交互测试。
实际项目如何使用?
- 多步骤表单:用状态与消息区分输入、验证、成功和失败。
- API 集成:用
Command描述请求,通过成功或失败消息更新界面。[6][8] - 实时界面:使用
Subscription处理外部事件,使用ManagedResource管理连接生命周期。[6] - UI 组件:独立包
@foldkit/ui提供 Dialog、Menu 等有状态 Submodel,以及 Button 等无状态辅助函数;开发者负责标记与样式。[4] - 调试与 AI:DevTools 可查看状态和消息历史;独立 MCP 服务器可向代理提供运行时数据。[1][9]
连接 AI 工具时,不要将敏感信息放入 Model、消息历史或 Command 参数。官方文档将 DevTools MCP 视为高权限访问,并提醒固定端口会在无身份验证的情况下监听,不应在不可信网络中使用。[9] 请使用测试数据,而非真实令牌。
采用前考虑学习成本与安全
对于希望统一状态流的应用,Foldkit 值得评估;对小型静态网站或深度依赖 React 生态的应用,迁移成本可能高于收益。团队还需学习 Effect、Schema 和基于消息的状态转换。[1] 建议先用小组件或独立页面验证。
依赖审计: 2026-11-20 对上述安装执行 npm audit 时报告 6 项漏洞(中危 1、高危 3、严重 2)。结果包括开发依赖与传递依赖,不意味着所有问题都在 Foldkit 核心包中,也不意味着应用已被利用。结果会随时间和版本变化。请检查受影响包、暴露范围及修复版本,并在自动修复或强制升级前测试兼容性。
Sources
[3] https://github.com/foldkit/foldkit
[4] https://foldkit.dev/ui/overview
[5] https://foldkit.dev/get-started
[6] https://foldkit.dev/core/architecture
[8] https://foldkit.dev/core/commands
[9] https://foldkit.dev/ai/mcp
クリック、APIの応答、画面状態が増えると、現在の画面に至る経緯を追いにくくなります。Foldkit公式サイトで紹介されているFoldkitは、状態変更と非同期処理の流れを明示するEffectベースのTypeScriptフロントエンドフレームワークです。[1]
本記事では構造を確認し、公式スキャフォルダーでカウンターを作成・テストします。Effectが初めてなら、先にEffectの入門記事も参照できます。
Foldkitとは
FoldkitはEffectとThe Elm Architectureを基盤としています。状態をModel、出来事をMessageで表し、updateが次の状態を決め、viewが画面に反映します。[2][6]
ボタンクリックの流れは次のとおりです。
Click → Message → update → Model → view → UI
APIリクエストや遅延のような一度きりの副作用は、updateが直接実行せず、Commandを返します。ランタイムが処理を実行し、結果をMessageとして返します。[6][8] Effect自体はフロントエンドフレームワークではなく、Foldkitがその上にUIアプリの構造を提供します。
インストール前の確認
FoldkitはMITライセンスのオープンソースで、まだ1.0未満です。プロジェクトはマイナーバージョンでも破壊的変更があり得ると説明しています。[2][3] ロックファイルを維持し、依存関係を確認してください。
公式ガイドはNode.js 22.22.2以降を指定しています。[5] 実習ではNode.js 26とcreate-foldkit-app 0.41.0を使用しました。生成されたfoldkitと@foldkit/uiは0.170.0、effectは4.1.0でした。同時点のnpm最新foldkitは0.171.0で、スキャフォルダーのバージョンとは異なります。[10][11] 今後のバージョンやAPIは変わる可能性があります。
カウンターアプリを作る
新しい作業ディレクトリで実行します。--example counterはブラウザー専用のカウンターを選択し、スキャフォルダーが依存関係をインストールします。[5][11]
npx --yes create-foldkit-app@0.41.0 --name foldkit-counter --rendering spa --example counter --package-manager npm
cd foldkit-counter
npm run dev
ターミナルに表示されたローカルURLを開くと、数値と-、Reset、+のボタンが表示されます。+で増加し、Resetで初期値に戻ります。生成したアプリで+を2回押し、2が表示されることを確認しました。

公式Counterスターターをローカルで実行し、+を2回押した状態。(出典:Foldkit Counter例、2026-11-20撮影)
別のターミナル、または開発サーバー停止後に型検査、テスト、ビルドを実行します。
npm run typecheck
npm test
npm run build
検証環境では型検査とビルドが成功し、付属のテスト10件がすべて成功しました。この結果はその時点の依存関係と環境に限られます。
ModelとMessageはどこにあるか
Counterスターターのsrc/main.tsはModel、Message、update、init、viewを定義し、src/entry.tsがそれらを使ってランタイムを開始します。[5] 次は生成されたsrc/main.tsの抜粋です。全体ではないため、このコードでファイルを上書きしないでください。
import { Schema } from 'effect'
import { Runtime, type Update } from 'foldkit'
import { Document, HtmlBuilder } from 'foldkit/html'
import { defineMessageUnion } from 'foldkit/message'
import { modifyFields } from 'foldkit/struct'
import { Button } from '@foldkit/ui'
// MODEL
export const Model = Schema.Struct({ count: Schema.Number })
export type Model = typeof Model.Type
// MESSAGE
export const Message = defineMessageUnion({
ClickedDecrement: {},
ClickedIncrement: {},
ClickedReset: {},
})
export type Message = typeof Message.Type
// UPDATE
export const update = (model: Model, message: Message) =>
Message.match<Update.Return<Model, Message>>(message, {
ClickedDecrement: () => ({
model: modifyFields(model, { count: count => count - 1 }),
}),
ClickedIncrement: () => ({
model: modifyFields(model, { count: count => count + 1 }),
}),
ClickedReset: () => ({ model: modifyFields(model, { count: () => 0 }) }),
})
Modelは数値の状態、Messageは3つのボタンの出来事を定義します。updateは次のモデルを返し、同じファイルのviewがボタンと値を描画します。初期値はinit、実行の接続はentry.tsにあります。src/story.test.tsとsrc/scene.test.tsで状態遷移と操作のテストも比較できます。
実際の活用例
- 複数ステップのフォーム:入力、検証、成功、失敗を状態とメッセージに分けます。
- API連携:リクエストを
Commandで表し、成功・失敗のメッセージで画面を更新します。[6][8] - リアルタイム画面:外部イベントには
Subscription、接続の寿命にはManagedResourceを利用できます。[6] - UI構築:別パッケージの
@foldkit/uiにはDialogやMenuなどの状態を持つSubmodelと、Buttonなどの状態を持たないヘルパーがあります。マークアップとスタイルは開発者が指定します。[4] - デバッグとAI:DevToolsで状態・メッセージ履歴を確認でき、別のMCPサーバーでエージェントにランタイム情報を渡せます。[1][9]
AI接続時はModel、メッセージ履歴、Command引数に機密情報を入れないでください。公式文書はDevTools MCPを高い権限を持つアクセスとして扱い、固定ポートは認証なしで受信するため、信頼できないネットワークで使わないよう警告しています。[9] 実際のトークンではなくテストデータを使いましょう。
導入前の学習コストとセキュリティ
Foldkitは状態の流れを統一したいアプリに向く場合があります。一方、小規模な静的サイトやReactエコシステムに深く依存するアプリでは移行コストが上回ることもあります。チームはEffect、Schema、メッセージベースの状態遷移を学ぶ必要があります。[1] 全体を移行する前に小さなウィジェットや独立画面で検証してください。
依存関係の監査: 2026-11-20に上記の環境でnpm auditを実行したところ、脆弱性6件(中1、高3、重大2)が報告されました。開発依存と間接依存を含む結果であり、すべてがFoldkit本体の問題であることや実際に悪用されたことを意味しません。結果はバージョンや時期で変わります。対象パッケージ、影響範囲、修正版を確認し、自動修正や強制アップグレードの前に互換性を検証してください。
Sources
[3] https://github.com/foldkit/foldkit
[4] https://foldkit.dev/ui/overview
[5] https://foldkit.dev/get-started
[6] https://foldkit.dev/core/architecture
[8] https://foldkit.dev/core/commands
[9] https://foldkit.dev/ai/mcp
Cuando aumentan los clics, las respuestas de API y los estados de pantalla, resulta difícil seguir cómo llegó la interfaz a su estado actual. Foldkit es un framework frontend TypeScript basado en Effect que hace explícitos los cambios de estado y el trabajo asíncrono.[1]
Esta guía explica su arquitectura y crea y prueba un contador con el generador oficial. Si Effect es nuevo para ti, consulta nuestra introducción a Effect.
¿Qué es Foldkit?
Foldkit se basa en Effect y The Elm Architecture. Representa el estado como Model, transmite eventos como Message, determina el siguiente estado en update y lo renderiza mediante view.[2][6]
El flujo de un clic es el siguiente:
Click → Message → update → Model → view → UI
Para un efecto puntual como una petición a una API o una espera, update devuelve un Command en lugar de ejecutar el trabajo directamente. El entorno de ejecución lo realiza y devuelve el resultado como Message.[6][8] Effect no es en sí un framework frontend; Foldkit aporta la arquitectura de interfaz sobre Effect.
Antes de instalar
Foldkit es software abierto con licencia MIT y todavía está por debajo de la versión 1.0. El proyecto advierte que incluso una versión menor puede introducir cambios incompatibles.[2][3] Conserva el archivo de bloqueo y revisa las dependencias.
La guía oficial exige Node.js 22.22.2 o posterior.[5] Probamos el ejemplo con Node.js 26 y create-foldkit-app 0.41.0. El proyecto generado instaló foldkit y @foldkit/ui 0.170.0 y effect 4.1.0. En ese momento, la última versión de foldkit en npm era 0.171.0: no hay que confundir la versión del generador con la del framework generado.[10][11] Las versiones y API pueden cambiar.
Crear un contador
Ejecuta estos comandos en un directorio de trabajo nuevo. --example counter selecciona el contador para navegador y el generador instala las dependencias.[5][11]
npx --yes create-foldkit-app@0.41.0 --name foldkit-counter --rendering spa --example counter --package-manager npm
cd foldkit-counter
npm run dev
Abre en el navegador la dirección local que aparece en la terminal. Verás un número y los botones -, Reset y +. + aumenta el valor y Reset lo devuelve al valor inicial. Ejecutamos el proyecto y confirmamos que dos clics en + mostraron 2.

Contador oficial ejecutado localmente después de pulsar + dos veces. (Fuente: ejemplo Counter de Foldkit, captura del 2026-11-20)
En otra terminal, o después de detener el servidor de desarrollo, comprueba tipos, pruebas y compilación:
npm run typecheck
npm test
npm run build
En el entorno de verificación, la comprobación de tipos y la compilación terminaron correctamente y pasaron las 10 pruebas incluidas. El resultado corresponde a esas dependencias y a ese entorno, no garantiza todos los entornos posibles.
¿Dónde están Model y Message?
En el contador, src/main.ts define Model, Message, update, init y view; src/entry.ts los importa e inicia el entorno de ejecución.[5] El siguiente código es solo un fragmento del src/main.ts generado. No reemplaces el archivo completo con él.
import { Schema } from 'effect'
import { Runtime, type Update } from 'foldkit'
import { Document, HtmlBuilder } from 'foldkit/html'
import { defineMessageUnion } from 'foldkit/message'
import { modifyFields } from 'foldkit/struct'
import { Button } from '@foldkit/ui'
// MODEL
export const Model = Schema.Struct({ count: Schema.Number })
export type Model = typeof Model.Type
// MESSAGE
export const Message = defineMessageUnion({
ClickedDecrement: {},
ClickedIncrement: {},
ClickedReset: {},
})
export type Message = typeof Message.Type
// UPDATE
export const update = (model: Model, message: Message) =>
Message.match<Update.Return<Model, Message>>(message, {
ClickedDecrement: () => ({
model: modifyFields(model, { count: count => count - 1 }),
}),
ClickedIncrement: () => ({
model: modifyFields(model, { count: count => count + 1 }),
}),
ClickedReset: () => ({ model: modifyFields(model, { count: () => 0 }) }),
})
Model define el estado numérico, Message declara los tres eventos y update devuelve el siguiente modelo. view, en el mismo archivo, renderiza botones y valor; init establece el valor inicial y entry.ts conecta el entorno de ejecución. Revisa src/story.test.ts y src/scene.test.ts para comparar pruebas de transición e interacción.
¿Cómo aplicarlo?
- Formularios de varios pasos: separar entrada, validación, éxito y error mediante estados y mensajes.
- Integración con API: describir una petición con
Commandy actualizar la pantalla con mensajes de éxito o error.[6][8] - Interfaces en tiempo real: usar
Subscriptionpara eventos externos yManagedResourcepara el ciclo de vida de una conexión.[6] - Componentes UI: el paquete independiente
@foldkit/uiincluye Submodels con estado como Dialog y Menu y utilidades sin estado como Button. El desarrollador define marcado y estilos.[4] - Depuración e IA: DevTools permite examinar el estado y el historial de mensajes; un servidor MCP independiente puede dar acceso a datos de ejecución a un agente.[1][9]
Al conectar herramientas de IA, mantén los datos sensibles fuera del Model, el historial de mensajes y los argumentos de Command. La documentación trata DevTools MCP como acceso privilegiado y advierte que un puerto fijo escucha sin autenticación; no lo uses en redes no confiables.[9] Usa datos de prueba en lugar de tokens reales.
Antes de adoptar: aprendizaje y seguridad
Foldkit puede ser adecuado para aplicaciones que necesitan una convención compartida de flujo de estado. En un sitio estático pequeño o una aplicación muy ligada al ecosistema React, la migración puede costar más de lo que aporta. El equipo también debe aprender Effect, Schema y transiciones basadas en mensajes.[1] Evalúa primero un widget pequeño o una pantalla independiente.
Auditoría de dependencias: el 2026-11-20, npm audit del proyecto anterior informó de 6 vulnerabilidades (1 moderada, 3 altas y 2 críticas). El resultado incluye dependencias de desarrollo y transitivas; no significa que todos los problemas pertenezcan al paquete central de Foldkit ni que la aplicación haya sido explotada. Los resultados cambian según la fecha y las versiones. Revisa paquetes, exposición y versiones corregidas, y prueba la compatibilidad antes de aplicar correcciones automáticas o actualizaciones forzadas.
Sources
[3] https://github.com/foldkit/foldkit
[4] https://foldkit.dev/ui/overview
[5] https://foldkit.dev/get-started
[6] https://foldkit.dev/core/architecture
[8] https://foldkit.dev/core/commands
[9] https://foldkit.dev/ai/mcp