Missing tokens no longer abort the run. The credential is still created and still attached to every node that needs it, holding a placeholder — so the workflows open without a missing-credential warning and nothing is left half-wired. They just cannot run until a real token is supplied. The placeholder is labelled in both places someone will look: the credential name becomes "Anthropic (seed, fake key)", which is what shows in the credential list and on every node, and the stored key is SEEDED-FAKE-KEY-not-a-real-credential, so a 401 in a log explains itself rather than raising a question about which key was used. The name is resolved once and used for the row, the cached name on each node, and the report, so those three cannot disagree. The report ends with what to do about it: which token each placeholder needs, where to generate it, and every place it can be set, each marked exists or create it. Re-running with the token set replaces the credential in place and keeps its id, so every node keeps pointing at it and the label drops away — verified by seeding placeholders and then re-seeding with real tokens. SEED_PLACEHOLDER_CREDENTIALS=1 forces placeholders even where a real token is available, for producing a database with no real keys in it or for seeing the estate as it looks before anything is configured.
20 KiB
AGENTS.md
This file provides guidance on how to work with the n8n repository.
Project Overview
n8n is a workflow automation platform written in TypeScript, using a monorepo structure managed by pnpm workspaces. It consists of a Node.js backend, Vue.js frontend, and extensible node-based workflow engine.
General Guidelines
- Always use pnpm
- Secrets on the command line: if a developer opted into anonymous dev
metrics (
scripts/dev-metrics), pnpm command arguments are recorded. Arguments of secret-carrying words (config,login,publish,token) — whether a subcommand or baked into a flag — are dropped, and the home dir is stripped from paths, but other args are sent as-is — so never put secrets in a command. Pass sensitive values via environment variables, which are never captured. - When adding comments, keep them concise and to the point - explain the "why" in a line or two; don't be overly verbose. Comments should be scoped and relevant to the surrounding code, not just to the current task
- We use Linear as a ticket tracking system
- We use Posthog for feature flags
- To find registered telemetry events (names, descriptions, properties), run
pnpm --filter @n8n/telemetry catalog(--jsonfor structured output). The registry is being adopted incrementally, so search call sites if the catalog has no match. Then8n:telemetryskill covers adding or changing events - When starting to work on a new ticket – create a new branch from fresh master with the name specified in Linear ticket
- When creating a new branch for a ticket in Linear - use the branch name suggested by Linear, unless it is a security fix (see Security Fix Hygiene below)
- Use mermaid diagrams in MD files when you need to visualise something
- Developing v3 features: land normal feature work on
masterbehind an opt-in flag; introduce breaking changes only on the3.xbranch. See .github/DEVELOPING_V3.md.
Agent Skills and Claude Code Plugin
n8n shared skills live in .agents/skills/. Claude Code consumes them through
symlinks in .claude/plugins/n8n/skills/; OpenCode reads .agents/skills/
directly. Harness-specific overrides remain real directories in the harness
path, such as .opencode/skills/setup-mcps/. See
skills README for editing and sync guidance.
n8n-specific Claude Code commands and agents live in .claude/plugins/n8n/ and
are namespaced under n8n:. Use n8n: prefix when invoking them (e.g.
/n8n:create-pr, /n8n:plan, n8n:developer agent). See
plugin README for structure and details.
Essential Commands
Fresh checkout / agent setup
For a fresh checkout (cat-bot, a new hire, any agent verifying the repo
builds), prefer pnpm agent:setup over running install + build + tests by
hand. It chains them in one process, caps per-process memory and turbo
concurrency so a 6GB box doesn't OOM, streams all output to
.agent-setup/<step>.log (gitignored), and surfaces only a one-line summary
per step plus the tail of the failing log. A machine-readable
.agent-setup/summary.json is always written so a backgrounded run is
readable in a single shot — no polling, no scrolling logs.
pnpm agent:setup # install → build → test (full suite)
pnpm agent:setup install # one step at a time
pnpm agent:setup --json # JSON summary on stdout (for scripts/agents)
Building
Use pnpm build to build all packages. ALWAYS redirect the output of the
build command to a file:
pnpm build > build.log 2>&1
You can inspect the last few lines of the build log file to check for errors:
tail -n 20 build.log
If build outputs or the turbo cache are stale (e.g. after switching branches
or worktrees) but dependencies haven't changed, use pnpm reset (lightweight
by default) for a fast recovery: it cleans build outputs and force-rebuilds
(keeping node_modules and untracked files). If that doesn't fix your issue,
use pnpm reset --full, which also wipes untracked files and reinstalls
dependencies.
Seeding a local instance with realistic data
An empty instance is a bad place to test anything that reasons about a user's work. Two seeds exist, and they do different jobs:
pnpm seed:account # one plausible account: 10 workflows, credentials, runs, AI threads
pnpm inspect:activity # a one-page viewer for the activity_event table
pnpm seed:account fills a local SQLite instance with a small, deliberately
consistent estate — ten workflows that all use the Anthropic chat model and all
touch Linear, the two data tables they read, working credentials built from
your own API tokens, a fortnight of execution history, Instance AI
conversations about those workflows, and (on builds that have the migration) a
matching activity log. ANTHROPIC_API_KEY and LINEAR_API_KEY are
optional — supply them (shell or packages/cli/.env) and the workflows run for
real; leave them out and the credentials are still created and attached, holding
a placeholder labelled (seed, fake key), so nothing is half-wired. Re-running
with a token set upgrades the credential in place.
Reach for it whenever you need an instance that looks used: manual UI checks,
demos, anything reading execution history, data tables, AI threads, or the
activity log. Its consistency is deliberate — for every job where n8n offers
a choice, exactly one node is used everywhere, so it doubles as a fixture for
anything reasoning about what a user tends to reach for. Adding a workflow means
following the CHOICES table in the script rather than picking again.
pnpm inspect:activity serves a single page on 127.0.0.1:5699 showing every
column of activity_event, paginated, sortable on any column, with a free-text
filter that searches the JSON data column too — so a run id or a failing node
name finds its entry without knowing which field holds it. Read-only, no build
step, no dependency, and loopback-only; it is a debug surface, not a product
page, and the whole table is served unauthenticated to anything that can reach
the port.
For a large synthetic org instead — ~500 workflows across ~30 projects, for
dependency-graph and perf work — use scripts/instance-seeding/seedInstance.mjs.
Both are documented in
scripts/instance-seeding/AGENTS.md,
including why credentials cannot be shared in a seed file.
Testing
pnpm test- Run all testspnpm test:affected- Runs tests based on what has changed since the last commit
Running a particular test file requires going to the directory of that test
and running: pnpm test <test-file>.
When changing directories, use pushd to navigate into the directory and
popd to return to the previous directory. When in doubt, use pwd to check
your current directory.
Code Quality
pnpm lint- Lint codepnpm typecheck- Run type checks
Always run lint and typecheck before committing code to ensure quality.
Execute these commands from within the specific package directory you're
working on (e.g., cd packages/cli && pnpm lint). Run the full repository
check only when preparing the final PR. When your changes affect type
definitions, interfaces in @n8n/api-types, or cross-package dependencies,
build the system before running lint and typecheck.
Architecture Overview
Monorepo Structure: pnpm workspaces with Turbo build orchestration
Package Structure
The monorepo is organized into these key packages:
packages/@n8n/api-types: Shared TypeScript interfaces between frontend and backendpackages/workflow: Core workflow interfaces and typespackages/core: Workflow execution enginepackages/cli: Express server, REST API, and CLI commandspackages/frontend/editor-ui: Vue 3 frontend applicationpackages/frontend/@n8n/i18n: Internationalization for UI textpackages/nodes-base: Built-in nodes for integrationspackages/@n8n/nodes-langchain: AI/LangChain nodespackages/@n8n/instance-ai: "AI Assistant" in the UI, "Instance AI" in code — AI assistant backend. See itsCLAUDE.mdfor architecture docs.@n8n/design-system: Vue component library for UI consistency@n8n/config: Centralized configuration management
Technology Stack
- Frontend: Vue 3 + TypeScript + Vite + Pinia + Storybook UI Library
- Backend: Node.js + TypeScript + Express + TypeORM
- Testing: Vitest (unit) + Playwright (E2E)
- Database: TypeORM with SQLite/PostgreSQL support
- Code Quality: Biome (for formatting) + ESLint + lefthook git hooks
Key Architectural Patterns
- Dependency Injection: Uses
@n8n/difor IoC container - Controller-Service-Repository: Backend follows MVC-like pattern
- Event-Driven: Internal event bus for decoupled communication
- Context-Based Execution: Different contexts for different node types
- State Management: Frontend uses Pinia stores
- Design System: Reusable components and design tokens are centralized in
@n8n/design-system, where all pure Vue components should be placed to ensure consistency and reusability
Key Development Patterns
- Each package has isolated build configuration and can be developed independently
- Hot reload works across the full stack during development
- Node development uses dedicated
node-devCLI tool - Workflow tests are JSON-based for integration testing
- AI features have dedicated development workflow (
pnpm dev:ai)
Workflow Traversal Utilities
The n8n-workflow package exports graph traversal utilities from
packages/workflow/src/common/. Use these instead of custom traversal logic.
Key concept: workflow.connections is indexed by source node.
To find parent nodes, use mapConnectionsByDestination() to invert it first.
import { getParentNodes, getChildNodes, mapConnectionsByDestination } from 'n8n-workflow';
// Finding parent nodes (predecessors) - requires inverted connections
const connectionsByDestination = mapConnectionsByDestination(workflow.connections);
const parents = getParentNodes(connectionsByDestination, 'NodeName', 'main', 1);
// Finding child nodes (successors) - uses connections directly
const children = getChildNodes(workflow.connections, 'NodeName', 'main', 1);
TypeScript Best Practices
- NEVER use
anytype - use proper types orunknown - Avoid type casting with
as- use type guards or type predicates instead (except in test code whereasis acceptable) - Define shared interfaces in
@n8n/api-typespackage for FE/BE communication - Lazy-load heavy modules — if a module is only used in a specific code
path (not every request), use
await import()at point of use instead of top-levelimport. Applies especially to native modules and large parsers.
Error Handling
- Don't use the deprecated
ApplicationErrorclass anywhere — it's a compatibility shim kept only so community nodes keep resolving. Use one of these instead, picking by cause:UserError— the user caused it (invalid input, unauthorized action, business-rule violation).OperationalError— a transient, expected issue (network request failing, DB query timing out) that should be handled gracefully.UnexpectedError— a bug in the code (logic mistake, unhandled case, failed assertion) that developers need to fix.
- Import from appropriate error classes in each package
Persistence layer & the TypeORM boundary
TypeORM (@n8n/typeorm) must stay in the persistence layer — the @n8n/db
package or a backend module's own database/ folder (entity/repository files).
Business logic — services, controllers, handlers, commands, factories — must not
import from @n8n/typeorm (including @n8n/typeorm/... subpaths). In
packages/cli this is enforced by the misplaced-n8n-typeorm-import lint rule;
a new import (or an inline eslint-disable of the rule) fails CI.
- Pattern: when a query needs operators (
In,IsNull,LessThan,FindOptionsWhere, …), put it behind a use-case-named repository method that takes plain parameters and returns domain-shaped values — not a genericfind(options)passthrough. - Transactions: transaction orchestration belongs in the persistence layer.
Don't reach for
.manager/.manager.transaction(...)orcreateQueryBuilder(...)in business logic. Use the sanctioned primitive in@n8n/db: inject the abstractTransactionRunnerand wrap the unit of work intxRunner.run(ctx, async (ctx) => …). The callback receives anOperationContextcarrying the active transaction; thread thatctxinto the repository methods you call.runrequires a context — pass an empty{}at the operation entry point, and reuse the one you were handed everywhere below it (a context that already carries a transaction is joined, not nested). Repositories extendBaseRepositoryand resolve the rightEntityManagerwiththis.managerFor(ctx); theTransactionhandle is opaque and never exposes a driver type to business logic. Seeoauth-token.service.ts+oauth-*-token.repository.tsfor a worked example. - Anti-patterns reviewers reject — they hide the dependency instead of
removing it:
- String-matching TypeORM errors, e.g.
error.name === 'QueryFailedError'. - Relabeling the import from
@n8n/typeormto@n8n/dbto silence the rule (@n8n/dbre-exports several operators/types, but this relabels the dependency rather than removing it). - Pushing
.manager/createQueryBuilderinto business logic to avoid an operator import — trades a visible leak for an invisible one.
- String-matching TypeORM errors, e.g.
Frontend Development
- Refer to
packages/frontend/AGENTS.md - All UI text must use i18n - add translations to
@n8n/i18npackage - Use CSS variables directly - never hardcode spacing as px values
- data-testid must be a single value (no spaces or multiple values)
- Always use
design-system-rulesskill in reviews
Testing Guidelines
- Always work from within the package directory when running tests
- Mock all external dependencies in unit tests
- Prefer reusing hoisted shared
mock<T>(...)fixtures when a typed mock is immutable and used across tests. This rule exists to avoid massive test slowdowns from repeatedly creating nested proxy mocks while preserving the type contract. Avoid replacing these withas unknown as Thelpers for entities likeUser. - Confirm test cases with user before writing unit tests
- Typecheck is critical before committing - always run
pnpm typecheck - When modifying pinia stores, check for unused computed properties
- For Vitest packages that use
@n8n/didecorators, usecreateVitestConfigWithDecoratorsfrom@n8n/vitest-config/node-decorators. It enables SWCdecoratorMetadata(esbuild doesn't emit it) and externalizes workspace packages that register services (@n8n/di,@n8n/config,@n8n/constants,n8n-workflow) so a single DIContainerinstance is shared across the runtime. Loading them through Vitest's pipeline alongside their CJS dist produces twoContainers andContainer.get(...)returnsundefined.
What we use for testing and writing tests:
- For testing nodes and other backend components, we use Vitest for unit tests. Examples can be found in
packages/nodes-base/nodes/**/*test*. - We use
nockfor server mocking - For frontend we use
vitest - For E2E tests we use Playwright. Run with
pnpm --filter=n8n-playwright test:local. Seepackages/testing/playwright/README.mdfor details. - To iterate on a feature without docker rebuilds, boot service containers
and run the dev servers locally —
pnpm --filter n8n-containers services --services postgres,redis,mailpit,proxythenpnpm dev:be(backend on 5678). For frontend hot reload, also runpnpm dev:fe:editor(8080). The rootpnpm devdoes not exist: it prints a notice and exits with code 0, thuspnpm dev && …looks successful but no server runs. See Develop against running containers. - In a codespace agent session, use
pnpm dev:up. It installs the missing dependencies, starts the backend, waits for health, shares the port with the org, and prints the URL. See .devcontainer/codespaces/README.md. - For Playwright test maintenance/cleanup, see
packages/testing/playwright/AGENTS.md(includes janitor tool for static analysis, dead code removal, architecture enforcement, and TCR workflows).
Common Development Tasks
When implementing features:
- Define API types in
packages/@n8n/api-types - Implement backend logic in
packages/climodule, followscripts/backend-module/backend-module-guide.md - Add API endpoints via controllers
- Update frontend in
packages/frontend/editor-uiwith i18n support - Write tests with proper mocks
- Run
pnpm typecheckto verify types
Design Principles
Security Must Not Degrade the Building Experience
Security improvements, whether driven by enterprise requirements or internal standards, must NEVER add friction to the common-case building experience. When designing security-related features (defaults, behaviors, flows, error handling), apply these checks:
- No friction for the common case: A community builder's workflow should remain intuitive. Security should be invisible when it can be.
- Migration and upgrade paths: Existing users must have a clear, non-disruptive path forward when defaults or behaviors change.
- Security layers on top, not in competition: Great UX and strong security are not trade-offs. They're both required. If a design forces a choice between them, the design needs more work.
Security Fix Hygiene
This is a public repository. When working on security fixes, never expose the attack vector or vulnerability type in any public-facing artifact. Attackers monitor open-source repos for signals like branch names, commit messages, PR titles, test descriptions, and Linear URLs.
Rules for security fixes:
- Branch names: Do NOT use the Linear-suggested branch name if it reveals
the vulnerability. Rename to describe the fix neutrally
(e.g.
node-1234-improve-request-handling, notnode-1234-fix-ddos-vulnerability). - Commit messages: Describe what the code now does, not the threat it
prevents (e.g.
fix: add payload size validation, notfix: prevent denial of service). - Test descriptions: Use neutral, functional language
(e.g.
'should sanitize query parameters', not'should prevent SQL injection'). - Code comments: Do not describe the attack scenario in comments.
- Linear references: Never include the URL slug
(e.g.
.../N8N-1234/fix-ssrf-vulnerability).
Customer Confidentiality
This is a public repository. Never mention customer names in any public-facing artifact — not all customers have agreed to be named publicly, and naming them can reveal security-relevant details about their setup.
This applies to PR titles and descriptions, branch names, commit messages,
code, code comments, test names and test data, and fixtures. When implementing
a customer request, describe the use case neutrally (e.g. "a customer with a
large multi-main setup", not the company name) and use generic placeholder
names (e.g. Acme Corp) in tests and examples.
Github Guidelines
- When creating a PR, use the conventions in
.github/pull_request_template.mdand.github/pull_request_title_conventions.md. - Use
gh pr create --draftto create draft PRs. - If there is a corresponding Linear ticket, reference it in the PR
description using
https://linear.app/n8n/issue/[TICKET-ID]. Do not create a Linear ticket on your own — ask first. - always link to the github issue if mentioned in the linear ticket.