
Figma
- 2 installs
- 2 repo stars
- Updated August 3, 2026
- fandhe-ai/agent-reference-skills
Reference Figma Code Connect batch files for mapping many Figma components to code with a single shared template, ideal for icon sets and large libraries.
About
A reference for Figma Code Connect batch files that connect many components to code via one shared template with enum-driven props. A developer loads it when wiring large Figma component libraries to code.
- Shared template file plus JSON component mapping
- Enum-based prop mapping for consistent patterns like icon sets
Figma by the numbers
- 2 all-time installs (skills.sh)
- Ranked #1,564 of 1,880 Design & UI/UX skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/fandhe-ai/agent-reference-skills --skill figmaAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2 |
|---|---|
| repo stars | ★ 2 |
| Last updated | August 3, 2026 |
| Repository | fandhe-ai/agent-reference-skills ↗ |
What it does
Reference Figma Code Connect batch files for mapping many Figma components to code with a single shared template, ideal for icon sets and large libraries.
Files
Batch Files
Connect many Figma components to code using a single shared template, ideal for large libraries with consistent patterns (e.g., icon sets).
Signature / Usage
Template file (icons.figma.batch.ts):
import figma from 'figma'
const size = instance.getEnum('Size', {
Small: '16px',
Medium: '24px',
Large: '32px',
})
export default {
example: figma.code`<${figma.batch.name} size={${size}} />`,
imports: [`import ${figma.batch.name} from "${figma.batch.importPath}"`],
id: figma.batch.id,
}JSON file (icons.figma.batch.json):
{
"templateFile": "./icons.figma.batch.ts",
"components": [
{
"url": "https://www.figma.com/design/ABC/File?node-id=1-1",
"name": "Icon24Arrow",
"id": "icon-arrow",
"importPath": "@company/icons/arrow"
}
]
}Options / Props
figma.batch object fields
| Field | Source | Description |
|---|---|---|
url | JSON url (required) | Replaces the // url= metadata comment |
source | JSON source (optional) | Replaces the // source= metadata comment |
component | JSON component (optional) | Replaces the // component= metadata comment |
| Custom fields | Any JSON field | Accessible as figma.batch.<fieldName> |
JSON file structure
Single template (shorthand):
{
"templateFile": "./template.figma.batch.ts",
"components": [ { "url": "...", ... } ]
}Multiple templates:
[
{ "templateFile": "./icons.figma.batch.ts", "components": [...] },
{ "templateFile": "./buttons.figma.batch.ts", "components": [...] }
]Notes
- Batch template files do not include metadata comments (
// url=,// source=,// component=) at the top — this data comes from the JSON file instead .figma.batch.jsonfiles are discovered automatically via existinginclude/excludeglobs (default globs already cover**/*.figma.batch.json)- Each component entry in the JSON publishes as an independent Code Connect document
- Publish with the standard
npx figma connect publishcommand
Related
- Template Files
- Template API
- CLI Reference
CI/CD Integration
Automate Code Connect publishing in CI/CD pipelines so that component connections stay up to date when code changes are merged.
Signature / Usage
Example GitHub Actions workflow:
name: Publish Code Connect
on:
push:
branches: [main]
paths:
- 'src/components/**/*.figma.tsx'
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npx figma connect publish --exit-on-unreadable-files
env:
FIGMA_ACCESS_TOKEN: ${{ secrets.FIGMA_ACCESS_TOKEN }}Notes
- Store the Figma personal access token in CI secrets as
FIGMA_ACCESS_TOKEN(must have Code ConnectWriteand File contentReadscopes) - Use
--exit-on-unreadable-filesto fail the pipeline on configuration errors - Restrict the workflow trigger to paths matching your Code Connect files to avoid running on every PR
- Establish local component connections first before setting up CI/CD automation
Related
- CLI Reference
- CLI Quickstart
- Config File
CLI Reference
Complete reference for the figma connect command and all its subcommands.
Signature / Usage
npx figma connect <command> [options]Options / Props
Global flags
| Flag | Description |
|---|---|
-t, --token <token> | Figma personal access token (alternatively set FIGMA_ACCESS_TOKEN env var) |
-v, --verbose | Enable debug logging |
-V, --version | Output version number |
-h, --help | Display help |
---
figma connect publish
Scan for Code Connect files and publish them to Figma.
npx figma connect publish [options]| Flag | Description |
|---|---|
-r, --dir <dir> | Directory to scan for Code Connect files |
-f, --file <file> | Single file to publish |
--dry-run | Preview changes without publishing |
--force | Overwrite existing UI-created mappings |
-l, --label <label> | Apply a publication label |
--exit-on-unreadable-files | Exit with error if any file cannot be read (recommended for CI/CD) |
---
figma connect unpublish
Remove published Code Connect connections from Figma.
npx figma connect unpublish [options]| Flag | Description |
|---|---|
-r, --dir <dir> | Directory to scan |
-f, --file <file> | Specific file to unpublish |
--node <link_to_node> | Target a specific Figma node URL (requires --label) |
-l, --label <label> | Label to unpublish for |
--dry-run | Preview changes without unpublishing |
Omitting --node unpublishes all components in the directory.---
figma connect parse
Parse Code Connect files and output them as JSON (without publishing).
npx figma connect parse [options]| Flag | Description |
|---|---|
-r, --dir <dir> | Directory to parse |
-f, --file <file> | Single file to parse |
--outFile <file> | Write JSON output to specified file |
-l, --label <label> | Apply label during parsing |
---
figma connect create
Generate a boilerplate Code Connect template file for a Figma component.
npx figma connect create <figma-node-url> [options]| Flag | Description |
|---|---|
--outDir <dir> | Output directory for the generated file |
---
figma connect preview
Preview how Code Connect snippets will render in the Inspect panel.
npx figma connect preview [dir/file] [options]| Flag | Description |
|---|---|
-r, --dir <dir> | Directory to scan |
--output <format> | Output format: table (default) or json |
---
figma connect migrate
Convert existing Code Connect files to template format.
npx figma connect migrate [options]| Flag | Description |
|---|---|
--outDir <dir> | Output directory for migrated files |
--javascript | Generate .figma.js instead of .figma.ts |
--include-props | Preserve metadata props in output |
Notes
- Set
FIGMA_ACCESS_TOKENas an environment variable to avoid passing--tokenon every command - Use
--exit-on-unreadable-filesin CI/CD pipelines to catch configuration errors early
Related
- CLI Quickstart
- Config File
- CI/CD Integration
Comparing Code Connect UI and CLI
Side-by-side comparison of the two Code Connect approaches to help teams choose the right tool.
Signature / Usage
Use the CLI when your team needs precise prop mapping and design-system snippets in Inspect:
# install, configure figma.config.ts, then publish
npx figma connect publishUse the UI (Dev Mode) when no local setup is desired or when mapping spans multiple frameworks simultaneously — open a component in Dev Mode and follow the guided connection flow.
Options / Props
| Aspect | CLI | UI |
|---|---|---|
| Setup location | Runs locally in repository | Integrated in Figma Dev Mode |
| MCP context provided | Component path, name, property mapping, dynamic code examples | Component path, name, user prompts, codebase context |
| Language support | Built-in parsers for React, Web Components, SwiftUI, Jetpack Compose; template files for any language | Language-agnostic; supports multiple frameworks simultaneously |
| Connections per component | Single mapping | One-to-many across frameworks |
| Code display in Inspect | Shows design system snippets | Displays file/component names only; AI-generated code preview |
| Property mapping | Full prop mapping with helpers | Not currently supported |
| Target audience | Engineering teams wanting precision and control | Mixed design-engineering teams; no local setup required |
Notes
- CLI-created connections appear in the UI but remain editable only via CLI
- UI scales better across organizations where non-developers participate in component mapping
- Both tools complement each other and both enhance Figma MCP server context
Related
- CLI Quickstart
- UI Setup
- Overview
Connecting Jetpack Compose Components
Connect Jetpack Compose components to Figma using Code Connect annotations and the Gradle plugin.
Signature / Usage
@FigmaConnect(url = "https://www.figma.com/file/...")
class ButtonDoc {
@FigmaProperty(FigmaType.Text, "Label")
val label = "Click me"
@FigmaProperty(FigmaType.Boolean, "Disabled")
val disabled = false
@FigmaProperty(FigmaType.Enum, "Type")
val type: ButtonType = Figma.mapping(
"Primary" to ButtonType.Primary,
"Secondary" to ButtonType.Secondary
)
@Composable
fun Component() {
Button(label = label, disabled = disabled, type = type)
}
}Options / Props
Gradle setup (required)
Add to build.gradle.kts:
| Dependency | Version |
|---|---|
com.figma.code.connect plugin | v1.2.9 |
code-connect-lib | v1.1.3 |
| Kotlin | v2.2.10 |
Core annotations
| Annotation | Description |
|---|---|
@FigmaConnect(url = "...") | Links a class to a Figma component node URL |
@FigmaProperty(FigmaType, "PropName") | Maps a Figma design property to a Kotlin variable |
@FigmaVariant("PropName", "Value") | Restricts a connection class to a specific variant |
@FigmaChildren("LayerName", ...) | Renders code for nested instances by layer name |
FigmaType values
| Value | Maps to |
|---|---|
FigmaType.Text | String text property |
FigmaType.Boolean | Boolean property |
FigmaType.Enum | Variant/enum property |
FigmaType.Instance | Nested component instance |
Figma.mapping() helper
Creates property-to-code mappings for enums, booleans, and custom transformations:
// Enum mapping
val type: ButtonType = Figma.mapping(
"Primary" to ButtonType.Primary,
"Secondary" to ButtonType.Secondary
)
// Boolean-to-component mapping
@FigmaProperty(FigmaType.Boolean, "Has Icon")
val icon: @Composable () -> Unit = Figma.mapping(
true to { Icon(Icons.Default.Star) },
false to { }
)Variant-specific connections
@FigmaConnect(url = "https://...")
@FigmaVariant("Type", "Primary")
class PrimaryButtonDoc {
@Composable
fun Component() { PrimaryButton() }
}Notes
@FigmaChildrenaccepts one or more layer names as arguments- Ensure the Kotlin and plugin versions match the requirements listed above — mismatches cause build failures
Related
- Config File
- CLI Reference
- Comparing CLI and UI
figma.config.json
Project-level configuration file placed at the repository root that controls how Code Connect discovers, parses, and publishes component files.
Signature / Usage
{
"codeConnect": {
"include": ["**/*.figma.ts"],
"exclude": ["test/**", "build/**"],
"parser": "react",
"label": "React",
"language": "jsx"
}
}Options / Props
Common fields
| Field | Type | Description |
|---|---|---|
include | string[] | Glob patterns for Code Connect files to parse |
exclude | string[] | Glob patterns to exclude from parsing |
parser | string | Override auto-detection: react, html, swift, compose, custom |
label | string | Label shown in Figma Dev Mode for code snippets |
language | string | Syntax highlighting language (see supported values below) |
interactiveSetupFigmaFileUrl | string | Figma file URL used during interactive setup |
documentUrlSubstitutions | object | Key-value substitutions run on Figma node URLs (useful for multiple files) |
defaultBranch | string | Default branch name for source code link generation |
Supported language values: jsx, tsx, typescript, javascript, swift, kotlin, html, css, json, graphql, python, go, rust, bash, sql, xml, dart, cpp, ruby, plaintext
React-specific fields
| Field | Type | Description |
|---|---|---|
importPaths | object | Map glob patterns to package import paths (e.g., "src/components/*": "@ui/components") |
paths | object | Must mirror TypeScript tsconfig.json path aliases for correct import resolution |
imports | string[] | Override generated import statements with explicit strings |
SwiftUI-specific fields
| Field | Type | Description |
|---|---|---|
xcodeprojPath | string | Path to the .xcodeproj file (defaults to first found) |
swiftPackagePath | string | Alternative to xcodeprojPath for Package.swift projects |
sourcePackagesPath | string | Location of the Source Packages directory |
importMapping | object | Map glob patterns to module names for correct import resolution |
Custom parser fields
| Field | Type | Description |
|---|---|---|
parserCommand | string | Command to invoke the custom parser (e.g., node parser.js) |
Notes
- Auto-detection checks
package.jsonfor React/HTML projects andPackage.swift/*.xcodeprojfor Swift projects documentUrlSubstitutionsis particularly useful in monorepos or when maintaining multiple Figma files without editing every Code Connect file
Related
- CLI Quickstart
- CLI Reference
- Template Files
- Custom Parsers
Custom Parsers
Enable Code Connect support for languages not natively supported by implementing a custom parser. Currently in preview.
Signature / Usage
{
"codeConnect": {
"parser": "custom",
"parserCommand": "node ../parserDirectory/parser.js",
"include": ["**/*.figma.test"],
"exclude": []
}
}Options / Props
figma.config.json fields for custom parsers
| Field | Type | Description |
|---|---|---|
parser | "custom" | Must be set to "custom" to activate |
parserCommand | string | Shell command to invoke the parser (receives file paths as arguments) |
include | string[] | File glob patterns to pass to the parser |
Input payloads
`ParseRequestPayload` (sent during publish / parse):
| Field | Description |
|---|---|
| File paths | List of matched files to process |
| Parser config | Configuration object from figma.config.json |
`CreateRequestPayload` (sent during create):
| Field | Description |
|---|---|
| Destination directory | Where to write the generated file |
| Optional filename | Suggested file name |
| Source filepath + export info | Code component location |
| Figma component metadata | Component id, name, type, properties |
| Parser config | Configuration object |
Output payloads
`ParseResponsePayload` (returned via stdout during publish / parse):
| Field | Required | Description |
|---|---|---|
| Code Connect documents array | Yes | Documents with template code and template data |
props mapping | Yes | Prop name to prop helper mappings |
imports | Yes | Import statements for the snippet |
language | Yes | Syntax highlighting language identifier |
| Messages (info/warning/error) | No | Feedback messages for the CLI to display |
`CreateResponsePayload` (returned via stdout during create):
| Field | Description |
|---|---|
| Created file paths | List of files the parser created |
| Parser messages | Info, warning, or error messages |
Notes
- The API is still evolving — provide feedback via GitHub issues
- The parser command is invoked with file paths from the
includeglobs; it must write itsParseResponsePayloadto stdout - Uses the Template API for generating Code Connect documents
Related
- Template API
- Config File
- CLI Reference
Connecting Web Components (HTML)
Connect HTML-based components — Web Components, Angular, Vue, or any HTML framework — to Figma using figma.connect() with the html tagged template literal.
Signature / Usage
import figma, { html } from '@figma/code-connect/html'
figma.connect('https://www.figma.com/file/...', {
props: {
label: figma.string('Label'),
disabled: figma.boolean('Disabled'),
type: figma.enum('Type', { Primary: 'primary', Secondary: 'secondary' }),
},
example: ({ label, disabled, type }) =>
html`<ds-button type="${type}" ?disabled="${disabled}">${label}</ds-button>`,
})Options / Props
Prop helpers
| Helper | Signature | Description |
|---|---|---|
figma.string | (propName: string) | Maps a Figma text property to a string value |
figma.boolean | (propName: string, mapping?: { true: T, false: T }) | Maps a boolean or two-option variant; optional conditional rendering |
figma.enum | (propName: string, mapping: Record<string, any>) | Maps a variant property to a code value |
figma.slot | (propName: string) | Maps a composable sub-area (slot) within the component |
figma.instance | (propName: string) | Maps a nested component reference |
figma.children | `(layerName: string \ | string[])` |
figma.nestedProps | (layerName: string, props: object) | Maps nested instance properties without connecting the child |
figma.textContent | (layerName: string) | Extracts text from a child layer |
figma.className | (values: any[]) | Concatenates class names, filtering undefined |
Variant restrictions
figma.connect('https://...', {
variant: { Type: 'Primary' },
example: () => html`<ds-button-primary></ds-button-primary>`,
})
figma.connect('https://...', {
variant: { Type: 'Danger', Disabled: true },
example: () => html`<ds-button-danger></ds-button-danger>`,
})Notes
- Code Connect files are not executed — the CLI treats code snippets as strings
- Any JavaScript/TypeScript logic accompanying HTML must be enclosed in a
<script>tag within the template - The same prop helpers are available for Angular, Vue, and other HTML-based frameworks; adjust the
htmltemplate syntax accordingly
Related
- React Integration
- Config File
- CLI Reference
Code Connect Overview
Bridges your codebase to Figma's Dev Mode by connecting design components to production code, enabling true-to-production code snippets instead of autogenerated examples.
Signature / Usage
Two implementation approaches:
- Code Connect CLI — command-line tool using template files; supports any codebase regardless of framework or language
- Code Connect UI — browser-based interface within Figma with GitHub integration; supports one-to-many connections across frameworks
Options / Props
| Aspect | CLI | UI |
|---|---|---|
| Setup | Runs locally in repository | Integrated in Figma Dev Mode |
| Language support | React, Web Components, SwiftUI, Jetpack Compose + any via templates | Language-agnostic, multiple frameworks |
| Connections | Single mapping per component | One-to-many across frameworks |
| Code display | Dev Mode Inspect panel snippets | File/component name + AI-generated previews |
| MCP context | Path, name, property mapping, dynamic examples | Path, name, user prompts, codebase context |
Notes
- Requires a Dev or Full seat in Figma on an Organization or Enterprise plan
- CLI-created connections appear in the UI but remain editable only via CLI
- Both tools complement each other and enhance the Figma MCP server for AI-guided workflows
- Personal access token must have Code Connect scope set to
Writeand File content scope set toRead
Related
- CLI Quickstart
- UI Setup
- Comparing CLI and UI
Getting Started with Code Connect CLI
Install the CLI, configure your project, write template or framework-specific files, and publish connections to Figma.
Signature / Usage
# Install globally
npm install --global @figma/code-connect@latest
# Publish all Code Connect files
npx figma connect publish --token=<PERSONAL_ACCESS_TOKEN>
# Or set token via environment variable
export FIGMA_ACCESS_TOKEN=<token>
npx figma connect publishOptions / Props
Requirements
| Requirement | Detail |
|---|---|
| Node.js | v18 or newer |
| Personal access token | Code Connect scope: Write; File content scope: Read |
Project configuration (figma.config.json)
{
"codeConnect": {
"include": ["**/*.figma.ts"],
"label": "React",
"language": "jsx"
}
}TypeScript type definitions (tsconfig.json)
{
"compilerOptions": {
"types": ["@figma/code-connect/figma-types"]
}
}Notes
- Adjust
labelandlanguageinfigma.config.jsonto match your framework (e.g.,"Swift"/"swift"for SwiftUI) - Template files use the
.figma.ts(or.figma.js) extension by convention - Each file requires a metadata comment
// url=https://www.figma.com/...pointing to the Figma component node
Related
- Config File Reference
- CLI Reference
- React Integration
- Template Files
Connecting React Components
Connect React components to Figma using figma.connect() with built-in prop helpers for mapping design properties to code.
Signature / Usage
import figma from '@figma/code-connect'
figma.connect(Button, 'https://www.figma.com/file/...', {
props: {
label: figma.string('Label'),
disabled: figma.boolean('Disabled'),
variant: figma.enum('Type', { Primary: 'primary', Secondary: 'secondary' }),
},
example: ({ label, disabled, variant }) => (
<Button disabled={disabled} variant={variant}>{label}</Button>
),
})Options / Props
figma.connect() signatures
// Connect a React component (infers import location)
figma.connect(ComponentRef, figmaNodeUrl, options)
// Connect without a component reference (native HTML element)
figma.connect(figmaNodeUrl, options)Prop helpers
| Helper | Signature | Description |
|---|---|---|
figma.string | (propName: string) | Maps a Figma text property to a string value |
figma.boolean | (propName: string, mapping?: { true: T, false: T }) | Maps a boolean or two-option variant; optional conditional rendering |
figma.enum | (propName: string, mapping: Record<string, any>) | Maps a variant property; keys are Figma options, values are code output |
figma.instance | (propName: string) | Renders a nested component reference with its connected snippet |
figma.children | `(layerName: string \ | string[])` |
figma.nestedProps | (layerName: string, props: Record<string, any>) | Maps properties of a nested instance without connecting it separately |
figma.textContent | (layerName: string) | Extracts text content from a child layer |
figma.className | (values: any[]) | Concatenates class name strings, filtering undefined values |
figma.instance() chainable methods
| Method | Description |
|---|---|
.getProps<T>() | Access child component props |
.render<T>(props => JSX) | Conditionally render using child component props |
figma.connect() options
| Option | Type | Description |
|---|---|---|
props | object | Map of prop names to prop helpers |
example | (props) => JSX | Function returning the code snippet |
imports | string[] | Import statements to include with the snippet |
variant | `Record<string, string \ | boolean>` |
Notes
- The first argument to
figma.connect()determines the import statement generated in Dev Mode figma.children()supports wildcard matching:'Icon*'matches all layers starting with "Icon",'*'matches all children- Code Connect files are not executed at runtime — they are treated as strings by the CLI
- Multiple
figma.connect()calls can target different variants of the same Figma component using thevariantoption
Related
- Config File
- Storybook Integration
- Template API
- CLI Reference
Code Connect
| Name | Description | Path |
|---|---|---|
| Overview | What Code Connect is, CLI vs UI summary, prerequisites, and MCP context | overview.md |
| Getting Started with CLI | Installation, project config, writing files, and publishing | quickstart.md |
| Getting Started with UI | Browser-based setup in Figma Dev Mode with multi-framework support | ui-setup.md |
| Connect to GitHub Repository | Link a GitHub repo to Code Connect UI for autocomplete and MCP context | ui-github.md |
| Comparing CLI and UI | Feature comparison table and suitability guide | comparing-cc.md |
| figma.config.json | All configuration fields for common, React, SwiftUI, and custom parser setups | config-file.md |
| Template Files | Framework-agnostic .figma.ts files: structure, metadata comments, and instance APIs | template-files.md |
| Template API | Complete API reference: figma object, InstanceHandle methods, helpers, and types | template-api.md |
| Batch Files | Connect many components via a single shared template and JSON manifest | batch-files.md |
| CLI Reference | All figma connect subcommands and flags | cli-reference.md |
| React Integration | figma.connect() with React prop helpers: string, boolean, enum, instance, children, etc. | react.md |
| Web Components (HTML) | figma.connect() for HTML, Web Components, Angular, Vue with the html template literal | html.md |
| SwiftUI Integration | FigmaConnect protocol and @FigmaString, @FigmaBoolean, @FigmaEnum property wrappers | swiftui.md |
| Jetpack Compose Integration | @FigmaConnect, @FigmaProperty, @FigmaVariant annotations and Figma.mapping() helper | compose.md |
| Storybook Integration | Connect Code Connect to React Storybook stories with variant restrictions | storybook.md |
| Custom Parsers | Implement a custom parser for unsupported languages (preview feature) | custom-parsers.md |
| CI/CD Integration | GitHub Actions workflow to automate publishing on code changes | ci-cd.md |
Integrating with Storybook
Connect Code Connect to Storybook stories so that design property changes in Figma generate code snippets from real stories.
Signature / Usage
import figma from '@figma/code-connect'
import { ButtonExample } from './Button.stories'
export default {
component: Button,
parameters: {
design: {
type: 'figma',
url: 'https://www.figma.com/file/...',
examples: [ButtonExample],
},
},
}Options / Props
parameters.design fields
| Field | Type | Description |
|---|---|---|
type | 'figma' | Must be 'figma' to activate the integration |
url | string | Figma component node URL |
examples | StoryFn[] | Array of story functions to use as code examples |
props | object | Prop helpers mapping Figma properties to story props |
imports | string[] | Import statements to include with the snippet |
Variant restrictions (when one Figma component maps to multiple stories)
examples: [
{ example: PrimaryButtonStory, variant: { Type: 'Primary' } },
{ example: SecondaryButtonStory, variant: { Type: 'Secondary' } },
]Dynamic props example
parameters: {
design: {
type: 'figma',
url: 'https://...',
props: {
label: figma.string('Text Content'),
disabled: figma.boolean('Disabled'),
type: figma.enum('Type', { Primary: 'primary', Secondary: 'secondary' }),
},
examples: [ButtonExample],
},
},Notes
- Storybook integration is React only
- This extends Figma's existing Storybook plugin, automatically embedding component previews in your documentation
- Individual story props can be overridden per example entry in the
examplesarray
Related
- React Integration
- CLI Reference
Connecting SwiftUI Components
Connect SwiftUI components to Figma using the FigmaConnect protocol and property wrapper helpers.
Signature / Usage
import Figma
struct Button_connection: FigmaConnect {
let component = Button.self
let figmaNodeUrl: String = "https://www.figma.com/file/..."
@FigmaString("Label") var label: String = "Click me"
@FigmaBoolean("Disabled") var disabled: Bool = false
@FigmaEnum("Type", mapping: ["Primary": ButtonType.primary, "Secondary": ButtonType.secondary])
var type: ButtonType = .primary
var body: some View {
Button(label, disabled: disabled, type: type)
}
}
// Use as an Xcode preview
#Preview { Button_connection() }Options / Props
Property wrappers
| Wrapper | Description |
|---|---|
@FigmaString("PropName") | Maps a Figma string property to a Swift String variable |
@FigmaBoolean("PropName") | Maps a Figma boolean property to a Swift Bool variable |
@FigmaEnum("PropName", mapping:) | Maps a Figma variant property to a Swift enum value using a dictionary |
@FigmaInstance("PropName") | Maps an instance-swap property to a nested component |
@FigmaChildren("LayerName") | Renders code snippets for nested instances not bound to instance-swap props |
@FigmaEnum / @FigmaBoolean options
| Option | Description |
|---|---|
hideDefault: true | Conceals the property when it shows its default value in Dev Mode |
Variant-specific connections
Use a separate struct with let variant to provide different code samples for specific component variants:
struct PrimaryButton_connection: FigmaConnect {
let component = Button.self
let figmaNodeUrl: String = "https://..."
let variant = ["Type": "Primary"]
var body: some View { PrimaryButton() }
}Conditional modifiers
// Apply a SwiftUI modifier conditionally based on a Figma property
@FigmaBoolean("Outlined") var outlined: Bool = false
var body: some View {
Button(label)
.figmaApply(outlined) { view in view.buttonStyle(.bordered) }
}Notes
@FigmaChildrenaccepts the name of the instance layer, not a property namefigmaApplyaccepts an optionalelseApplytrailing closure for the false branch- Connection structs work directly as Xcode previews via
#Preview { MyComponent_connection() } - Set
xcodeprojPathorswiftPackagePathinfigma.config.jsonif auto-detection fails
Related
- Config File
- CLI Reference
- Comparing CLI and UI
Template API
Core TypeScript/JavaScript API for building Code Connect template files. Provides the figma object, InstanceHandle methods, and type definitions.
Signature / Usage
import figma from 'figma'
const disabled = instance.getBoolean('Disabled')
const iconSnippet = instance.findInstance('Icon').executeTemplate().example
export default {
example: figma.code`<Button disabled={${disabled}}>${iconSnippet}</Button>`,
id: 'button-template',
metadata: { nestable: true },
}Options / Props
figma object
| Property / Method | Type | Description |
|---|---|---|
figma.selectedInstance | InstanceHandle | Currently selected layer |
figma.code | Tagged template literal | Builds ResultSection[] for the snippet; use instead of string concatenation |
figma.batch | object | Available in batch files; provides url, source, component, and custom JSON fields |
figma.helpers | object | Utility helpers for framework-specific rendering |
InstanceHandle — property access
| Method | Signature | Description |
|---|---|---|
getBoolean | `(propName: string, options?: Record<string, any>): boolean \ | any` |
getString | (propName: string): string | Retrieve a string property |
getEnum | (propName: string, options: Record<string, any>): any | Map a variant property to a code value |
getPropertyValue | `(propName: string): string \ | boolean` |
getInstanceSwap | (propName: string): InstanceHandle | Retrieve an instance-swap property |
getSlot | `(propName: string): ResultSection[] \ | undefined` |
hasCodeConnect | (): boolean | Whether the instance has a Code Connect document |
codeConnectId | `(): string \ | null` |
InstanceHandle — layer finding
| Method | Signature | Description |
|---|---|---|
findText | `(layerName: string, opts?: SelectorOptions): TextHandle \ | ErrorHandle` |
findInstance | `(layerName: string, opts?: SelectorOptions): InstanceHandle \ | ErrorHandle` |
findConnectedInstance | `(codeConnectId: string, opts?: SelectorOptions): InstanceHandle \ | ErrorHandle` |
findConnectedInstances | (selectorFn: (node: InstanceHandle) => boolean, opts?: SelectorOptions): InstanceHandle[] | Find all child instances matching a selector |
findLayers | `(selectorFn: (node) => boolean, opts?: SelectorOptions): (InstanceHandle \ | TextHandle \ |
InstanceHandle — execution
| Method | Returns | Description |
|---|---|---|
executeTemplate | { example: ResultSection[], metadata: Metadata } | Run the nested instance's template and return its snippet |
TextHandle
| Property | Type | Description |
|---|---|---|
textContent | string | The text layer's string content |
SelectorOptions
| Field | Type | Description |
|---|---|---|
path | string[] | Parent layer name hierarchy to restrict the search |
traverseInstances | boolean | Whether to search through nested instances |
figma.helpers.react — value type wrappers
| Helper | Description |
|---|---|
jsxElement(value) | Wrap a JSX element string |
function(value) | Wrap a function expression string |
identifier(value) | Wrap an identifier string |
object(value) | Wrap a plain object |
templateString(value) | Wrap a template string |
reactComponent(value) | Wrap a React component reference |
array(value) | Wrap an array |
renderProp(name, prop) | Render a prop as a JSX attribute string |
renderChildren(prop) | Render prop as JSX children |
renderPropValue(prop) | Render a prop value |
stringifyObject(obj) | Stringify an object for use in JSX |
isReactComponentArray(prop) | Check if value is an array of React components |
figma.helpers.swift / figma.helpers.kotlin
Both provide renderChildren(children: any, prefix: string): ResultSection[] for properly indented nested rendering.
ResultSection union types
| Type | Fields | Description |
|---|---|---|
CodeSection | type: 'CODE', code: string | A literal code string |
InstanceSection | type: 'INSTANCE', guid: string, symbolId: string | A linked component instance |
SlotSection | type: 'SLOT', guid: string | A slot reference |
ErrorSection | type: 'ERROR', message: string, errorObject?: ResultError | An error placeholder |
Notes
- Always use
figma.codetagged template literal instead of plain string concatenation to preserve pill rendering in Dev Mode figma.batchis only available inside.figma.batch.tstemplate files
Related
- Template Files
- Batch Files
- React Integration
Template Files
Framework-agnostic approach to defining Code Connect using TypeScript (.figma.ts) or JavaScript (.figma.js) files that give full control over code snippet generation.
Signature / Usage
// url=https://www.figma.com/file/ABC/DesignSystem?node-id=1-1
// source=src/components/Button.tsx
// component=Button
import figma from 'figma'
const label = instance.getString('Label')
const disabled = instance.getBoolean('Disabled')
export default {
example: figma.code`<Button disabled={${disabled}}>${label}</Button>`,
imports: ["import { Button } from '@ui/components'"],
id: 'button-template',
}Options / Props
Metadata comments (at file top)
| Comment | Required | Description |
|---|---|---|
// url= | Yes | URL of the Figma component node |
// source= | No | File path of the corresponding code component |
// component= | No | Component name |
Export object fields
| Field | Type | Required | Description |
|---|---|---|---|
example | ResultSection[] | Yes | Code snippet produced by figma.code tagged template literal |
imports | string[] | No | Import statements to include with the snippet |
id | string | No | Custom Code Connect identifier |
metadata.nestable | boolean | No | true = inline rendering; false = expandable pill |
metadata.props | object | No | Data passed to parent templates |
Instance property access methods
| Method | Description |
|---|---|
instance.getString(propName) | Retrieve a string property value |
instance.getBoolean(propName) | Retrieve a boolean property value |
instance.getEnum(propName, mapping) | Map an enum/variant property to a code value |
instance.getPropertyValue(propName) | Retrieve raw string or boolean value |
instance.findInstance(layerName) | Locate a nested component instance by layer name |
instance.getSlot(propName) | Reference a flexible content slot |
instance.findConnectedInstances(selectorFn) | Find child instances matching a selector function |
instance.executeTemplate() | Execute a nested instance's template and return its snippet |
Notes
- Configure
figma.config.jsonwithlabel,language, andinclude: ["**/*.figma.ts"]before using template files - Add
"types": ["@figma/code-connect/figma-types"]totsconfig.jsonfor type definitions - Use
figma.codetemplate literal (not plain string interpolation) to preserve pill rendering in Dev Mode - Use
getSlot()for freeform content that varies in structure; usefindConnectedInstances()when all children share the same component type npx figma connect migrateconverts existing Code Connect files to template format; use--outDir,--javascript,--include-propsflags as needed
Related
- Template API
- Batch Files
- Config File
- CLI Reference
Connect to GitHub Repository
Links a GitHub repository to a Figma library file in Code Connect UI, enabling file path autocomplete and enhanced Figma MCP server context.
Signature / Usage
1. Open Code Connect UI in your Figma library file 2. Click Settings → Connect to GitHub 3. Authenticate with your GitHub account 4. Select Install and Authorize and confirm repository access (requires admin or owner permissions) 5. Select the repository and designate component directories
Notes
- You must be the owner of the Figma library file or an organization admin to connect GitHub
- Only one repository can be linked per Figma library file
- GitHub Enterprise Server (GHES) is not supported
- Users without admin permissions must request access from their organization administrator
- Connected directories become available for component path autocomplete when mapping components
Related
- UI Setup
- Comparing CLI and UI
Getting Started with Code Connect UI
Browser-based interface within Figma Dev Mode for connecting design components to code without local CLI installation.
Signature / Usage
1. Open a Figma library file containing design components 2. Switch to Dev Mode 3. Select Library → Connect components to code from the dropdown 4. Map each component to its code file path and optional component name
Options / Props
| Feature | Details |
|---|---|
| GitHub integration | Optional; provides file path autocomplete and direct component browsing |
| Multiple frameworks | Map a single design component to multiple code implementations |
| Custom AI instructions | Add prompts that guide Figma MCP server code generation |
| AI preview | Preview generated code snippets by adjusting component properties in the UI |
Adding multiple framework connections
1. Connect the initial component 2. Hover over the component row to reveal the add button 3. Enter file path and name for each additional framework
Notes
- Requires Dev or Full seat on Organization/Enterprise plan
- UI mappings do not display code snippets in the Inspect panel (unlike CLI)
- GitHub Enterprise Server (GHES) is not supported
- Only one GitHub repository can be linked per Figma library file
- CLI-created connections appear in the UI but are editable only via CLI
Related
- Connect to GitHub Repository
- Comparing CLI and UI
- Overview
Add Custom Rules
Store project-level rules in your MCP client's configuration to guide AI output, reduce repetitive prompting, and ensure consistency across team workflows.
Signature / Usage
For Claude Code, add rules to CLAUDE.md:
# MCP Servers
## Figma MCP server rules
- Always use components from `/src/components/ui` when possible
- Prioritize design fidelity; avoid hardcoding values
- Use design tokens from Figma where available
- Follow accessibility standards (WCAG)
- If the Figma MCP Server returns a localhost source for an image or SVG, use that source directlyCheck your specific client's documentation for the correct configuration file and formatting.
Options / Props
Recommended rule categories:
| Category | Example rule |
|---|---|
| Component library path | "Always use components from /path/to/design-system" |
| Design tokens | "Use Figma variables for spacing, color, and typography" |
| Asset handling | "Use localhost image/SVG sources directly from the Figma payload" |
| Accessibility | "Follow WCAG accessibility standards" |
| Workflow | "Fetch design context first, then screenshots, then translate" |
Notes
- Rules act as documented best practices that persist across sessions
- To generate tailored rules automatically: prompt the agent to analyze your codebase and produce documentation covering design systems, component libraries, frameworks, and styling approaches
- Avoid creating new icon packages from scratch — assets should always originate from the Figma payload
- A structured workflow rule ensures quality: (1) fetch design context → (2) get screenshots → (3) download assets → (4) translate with project conventions → (5) reuse existing components → (6) validate against Figma
Related
- Write Effective Prompts
- Trigger Specific Tools
- Code Connect Integration
Avoid Large Frames
Large frame selections slow down tools, cause errors, or produce incomplete responses because there is too much context for the model to process at once.
Signature / Usage
# Preferred: work at the component level
"Generate code for the Card component in this frame"
"Implement the Header section"
"Build the Sidebar component"
# Avoid: entire screen in one call
"Generate code for this full dashboard screen"Notes
- Break down selections to individual components or smaller sections (e.g.,
Card,Header,Sidebar) - If a request feels slow or stuck, reduce your selection size and retry
- Keeping context manageable leads to more predictable outcomes for both user and model
- When troubleshooting quality issues, revisit three fundamentals: (1) how the Figma file is organized, (2) how prompts are written, (3) what context is passed to the model
Related
- Structure Figma File
- Write Effective Prompts
- Trigger Specific Tools
Code Connect Integration
Enhances Figma MCP server output with real implementation details from your codebase. When components are connected via Code Connect, the server wraps generated code in <CodeConnectSnippet> with design properties, import statements, usage examples, and custom instructions.
Signature / Usage
Two implementation approaches:
Code Connect CLI
Provides the richest output:
- Import statements from explicit
importsfields or auto-populatedsourcefields - Full user-defined code snippets showing direct implementation
- Detailed prop mappings and component source paths
Code Connect UI
Auto-generates content without a CLI:
- Import statements based on mapped component paths and names
- Snippets automatically created from design component names and current property values
- Custom instructions added through Add instructions for MCP in the UI
Options / Props
Context injected into <CodeConnectSnippet> by the MCP server:
| Field | Description |
|---|---|
| Design properties | Current variant values, boolean props, text content from Figma components |
| Import statements | How to import components from your library |
| Usage examples | Actual component implementation patterns from your codebase |
| Custom guidance | Team-specific conventions and best practices |
Notes
- Prioritize connecting frequently-used design system components first
- Document component-specific patterns using custom instructions in Code Connect UI
- Keep mappings synchronized with codebase changes to prevent stale suggestions
- Test and refine instructions using the Code Connect UI preview before rolling out
- Components must be published in Figma before Code Connect integration takes effect with write-to-canvas
Related
- Tools and Prompts
- Write to Canvas
- Desktop Server Installation
- Structure Figma File
Code to Canvas
Captures live UI from the browser and converts it into editable Figma frames using the generate_figma_design tool. Bridges code-first development with design collaboration by bringing real UI into Figma.
Signature / Usage
# Step 1: Install and configure the remote Figma MCP server for your client
# Step 2: Prompt to initiate capture
"Start a local server for my app and capture the UI in a new Figma file"
"Start a local server for my app and capture the UI in [existing file URL]"
"Capture the UI to my clipboard"After prompting, use the browser toolbar to select Entire screen or Select element for targeted capture.
Options / Props
| Requirement | Detail |
|---|---|
| Server | Remote Figma MCP server |
| Figma seat | Full seat required for files outside your drafts |
| File permission | Edit permission required to modify existing files |
Notes
- Captured frames become standard Figma design layers — fully editable, organizable, and annotatable
- Clients typically infer that subsequent captures should go to the same file
- For live web apps, use tools like Playwright to inject the required capture scripts
- Supports capturing a single screen or an entire multi-step flow in one session
Supported Clients
Augment, Claude Code, Codex by OpenAI, Cursor, Factory, Firebender, VS Code, Warp
Related
- Remote Server Installation
- Tools and Prompts
- Write to Canvas
Desktop Server Installation
Local Figma MCP server running in the Figma desktop app. Suited for specific organizational needs; remote server is recommended for most users.
Signature / Usage
Server URL: http://127.0.0.1:3845/mcp (HTTP transport, local only)
Step 1: Enable the desktop MCP server in Figma
1. Open the Figma desktop app (latest version) 2. Open or create a Design file 3. Switch to Dev Mode with Shift+D 4. In the MCP server section, click Enable desktop MCP server
Step 2: Configure your MCP client
Claude Code:
claude mcp add --transport http figma-desktop http://127.0.0.1:3845/mcpVS Code (requires GitHub Copilot):
Open Command Palette → MCP: Add Server → select HTTP → paste the server URL → use ID figma-desktop.
Cursor:
Settings → MCP tab → Add new global MCP server with URL http://127.0.0.1:3845/mcp.
Generic JSON config:
{
"mcpServers": {
"figma-desktop": {
"url": "http://127.0.0.1:3845/mcp"
}
}
}Step 3: Provide design context
Two methods to give the agent context:
- Selection-based: Select a frame in Figma, then prompt the client to implement the selection
- Link-based: Share a Figma node URL; the agent extracts the
node-idautomatically
Step 4: Adjust settings
Access settings via the MCP server inspect panel in the desktop app:
- Image handling: choose local server or download assets
- Code Connect: enable component reuse from your codebase
Notes
- Desktop server does not support remote-only tools (
create_new_file,generate_diagram,use_figma,upload_assets, etc.) - The Figma desktop app must remain open and connected for the server to be available
- Adjust settings panel is accessible through the MCP server section in Dev Mode
Related
- Remote Server Installation
- Tools and Prompts
- Code Connect Integration
Make Context and Resources
Fetch design and prototype files from Make projects through the MCP integration, enabling agents to reuse existing design context instead of starting from scratch.
Signature / Usage
# Example prompt workflow
1. Share a Make project link with the agent
2. Agent returns a list of available files in the project
3. Download desired files when promptedExample prompt:
"Here is my Make project link: [URL]. Extract the button component's behavior and styling for implementation."Options / Props
- Fetch project context directly from Make (individual files or whole project)
- Prompt the agent to use existing code components instead of creating new ones
- Extend prototypes with real data to validate and productionize designs faster
Notes
- This integration uses the MCP resources capability; only available on clients that support MCP resources
- Designed to reduce friction when transitioning Make prototypes into production applications
- Preserves design intent throughout implementation by reusing existing component definitions
Related
- Overview
- Code Connect Integration
- Write to Canvas
Figma MCP Server Overview
Integrates Figma into AI agent workflows via the Model Context Protocol (MCP), enabling design-to-code generation and writing native Figma content back to the canvas.
Signature / Usage
Two deployment options:
- Remote server (recommended): cloud-hosted at
https://mcp.figma.com/mcp; broadest feature set - Desktop server: locally hosted at
http://127.0.0.1:3845/mcp; for specific organizational needs
Options / Props
- Generate code from selected Figma frames with design context (variables, components, layout)
- Write native Figma content (frames, components, variables, auto layout) directly from MCP clients
- Retrieve Make file resources for prototype-to-production transitions
- Leverage Code Connect for consistency between generated code and actual components
Notes
- Only MCP clients listed in the Figma MCP Catalog can connect to the Figma MCP Server
- Write to canvas is in beta and currently free; will eventually become usage-based and paid
- Installing Figma skills for your MCP client is recommended for reliable write-to-Figma workflows
- Full Figma seat required for write operations; Dev seats are read-only
Related
- Remote Server Installation
- Desktop Server Installation
- Tools and Prompts
Figma MCP Server
| Name | Description | Path |
|---|---|---|
| Overview | What the Figma MCP Server is, key capabilities, and deployment options | overview.md |
| Remote Server Installation | Cloud-hosted server setup for Claude Code, Cursor, VS Code, and Codex | remote-server-installation.md |
| Desktop Server Installation | Local server setup via the Figma desktop app | desktop-server-installation.md |
| Tools and Prompts | Full reference for all 18 MCP tools and example prompts | tools-and-prompts.md |
| Make Context and Resources | Fetch design context from Make projects via MCP resources | make-context-resources.md |
| Write to Canvas | Create and modify native Figma content from an MCP client (beta) | write-to-canvas.md |
| Code to Canvas | Capture live browser UI as editable Figma frames | code-to-canvas.md |
| Code Connect Integration | Enrich generated code with real codebase implementation details | code-connect-integration.md |
| Structure Figma File | File organization best practices for better code generation | structure-figma-file.md |
| Write Effective Prompts | Prompt patterns that improve output precision and consistency | write-effective-prompts.md |
| Trigger Specific Tools | Force correct tool selection with explicit prompt phrasing | trigger-specific-tools.md |
| Add Custom Rules | Store project-level rules in client config to reduce repetitive prompting | add-custom-rules.md |
| Avoid Large Frames | Why and how to break down large selections for reliable results | avoid-large-frames.md |
Remote Server Installation
Cloud-hosted Figma MCP server setup. Recommended for the broadest feature set including write-to-canvas, diagram generation, and design system search.
Signature / Usage
Server URL: https://mcp.figma.com/mcp (HTTP/SSE transport)
Claude Code
# Preferred: plugin install
claude plugin install figma@claude-plugins-official
# Manual
claude mcp add --transport http figma https://mcp.figma.com/mcp
# For global access across all projects
claude mcp add --transport http --scope user figma https://mcp.figma.com/mcpThen authenticate via the /mcp command in Claude.
Cursor
# Preferred: in chat
/add-plugin figmaOr use the deep-link installer, then authenticate when prompted.
VS Code
{
"servers": {
"figma": {
"url": "https://mcp.figma.com/mcp",
"type": "http"
}
}
}Open Command Palette (⌘ Shift P) → select MCP configuration (user or workspace) → paste the JSON above → click Start → authorize access.
Codex
codex mcp add figma --url https://mcp.figma.com/mcpOr via app: Plugins → + → Install Figma, then authenticate.
Notes
- Authentication uses Figma OAuth; authorization is triggered on first use
- Remote server supports all tools including
create_new_file,generate_diagram,use_figma,upload_assets, and others marked remote-only - See Tools and Prompts for the full list of remote-only tools
Related
- Desktop Server Installation
- Tools and Prompts
- Write to Canvas
Structure Figma File
Best practices for organizing Figma files to maximize code generation quality when using the MCP server.
Options / Props
| Practice | Detail |
|---|---|
| Use components | Buttons, cards, inputs, nav items — anything repeated should be a component |
| Connect via Code Connect | The #1 way to get consistent component reuse in generated code |
| Apply Figma Variables | Use variables consistently for spacing, color, radius, and typography |
| Semantic layer naming | Replace Frame1268 with descriptive names like CardContainer or CTA_Button |
| Auto Layout | Makes designs more responsive and communicates layout intent clearly |
| Add Annotations | Convey design behaviors and intent that visuals alone cannot communicate |
| Include Dev Resources | Attach developer resource links to layers in Dev Mode for added context |
Notes
- Semantic layer names help the model comprehend functionality and purpose; generic names produce lower-quality code
- Auto Layout typically results in cleaner code without absolute positioning
- Code Connect eliminates guesswork for the AI model about which component to use
Related
- Code Connect Integration
- Write Effective Prompts
- Avoid Large Frames
Tools and Prompts
Complete reference for all tools and example prompts exposed by the Figma MCP Server.
Options / Props
Tools
| Tool | Description | Requires File | Remote Only |
|---|---|---|---|
add_code_connect_map | Maps Figma node IDs to codebase components | Figma Design | No |
create_new_file | Creates a new blank Figma Design, FigJam, or Figma Slides file | None | Yes |
generate_diagram | Converts Mermaid syntax or descriptions to FigJam diagrams | None | Yes |
generate_figma_design | Sends live UI as design layers to Figma files | Figma Design | Yes |
get_code_connect_map | Retrieves mappings between Figma instances and code components | Figma Design | No |
get_code_connect_suggestions | Detects suggested Code Connect mappings | Figma Design | No |
get_context_for_code_connect | Retrieves context for generating Code Connect templates | Figma Design | Yes |
get_design_context | Extracts design context (default output: React + Tailwind) | Figma Design, Make | No |
get_figjam | Returns FigJam metadata in XML format with screenshots | FigJam | No |
get_libraries | Returns subscribed and available design libraries | Figma Design | Yes |
get_metadata | Returns sparse XML representation of the current selection | Figma Design | No |
get_screenshot | Takes screenshots of selected elements | Design, FigJam, Slides | No |
get_variable_defs | Returns variables and styles used in the selection | Figma Design | No |
search_design_system | Searches across all connected design libraries | Figma Design | Yes |
send_code_connect_mappings | Confirms Code Connect mappings after suggestions | Figma Design | No |
upload_assets | Uploads PNG, JPG, GIF, WebP assets (max 10 MB) | Design, FigJam, Slides | Yes |
use_figma | General-purpose tool for creating/editing Figma objects | Design, FigJam, Slides | Yes |
whoami | Returns authenticated user identity and plan info | None | Yes |
Example Prompts
Code generation from design:
"Generate my Figma selection in Vue"
"Implement the selected frame using Chakra UI components"
"Generate iOS SwiftUI code from the selected Figma frame"File operations:
"Create a new Figma file called 'Homepage Redesign'"
"Add a new frame to my Figma file"Diagram creation (FigJam):
"Create a flowchart for the user authentication flow"
"Generate a Gantt chart for the project timeline"Design system & tokens:
"Search for a button component in my design system"
"Get the variable names and values used in this frame"
"Create a color variable collection from design tokens"Notes
- Tools marked Remote Only are unavailable when using the desktop server (
http://127.0.0.1:3845/mcp) get_design_contextoutputs React + Tailwind by default; specify another framework in your prompt to overrideuse_figmais the general write tool; prefer explicit prompt phrasing over relying on automatic tool selection (see Trigger Specific Tools)upload_assetshas a 10 MB per-file limit
Related
- Remote Server Installation
- Trigger Specific Tools
- Code Connect Integration
Trigger Specific Tools
AI assistants don't always select the right MCP tool automatically. Explicitly naming the desired tool or describing its output in your prompt forces correct tool selection.
Signature / Usage
# Force get_design_context
"Get the design context for my Figma selection"
# Force get_variable_defs — use explicit description of what you want
"Get the variable names and values used in this frame"
# Force get_screenshot
"Take a screenshot of my selection"
# Force get_metadata
"Get the metadata for the selected Figma layers"Options / Props
Key tools to trigger explicitly:
| Tool | When to trigger explicitly |
|---|---|
get_design_context | When you want structured React + Tailwind representation; adapt with framework instructions |
get_variable_defs | When you want design tokens (colors, spacing, typography) rather than generated code |
get_screenshot | When you need a visual reference rather than structured data |
get_metadata | When you want a sparse XML representation of the selection structure |
Notes
- If output seems incomplete or inaccurate, rephrasing to name the tool explicitly is the first troubleshooting step
get_design_contextserves as a foundation for any framework — pair it with framework instructions in your prompt- As the MCP server adds more tools, explicit tool references in prompts become increasingly important
Related
- Tools and Prompts
- Write Effective Prompts
- Add Custom Rules
Write Effective Prompts
Guidelines for crafting prompts that get precise, consistent output from the Figma MCP server. Treat prompting like briefing a teammate — specificity drives results.
Signature / Usage
# Specify framework and styling system
"Generate iOS SwiftUI code from the selected Figma frame"
"Implement the selected frame using Chakra UI components"
# Target your codebase conventions and file paths
"Generate this using components from src/components/ui"
"Add this component to src/components/marketing/PricingCard.tsx"
# Specify layout system
"Implement this using our Stack layout component"Options / Props
What a well-specified prompt controls:
| Aspect | Example |
|---|---|
| Framework or styling system | "React + Tailwind", "SwiftUI", "Chakra UI" |
| Codebase conventions | File structure, naming patterns, layout approaches |
| Output file path | src/pages, components/ui |
| Edit vs. create | "Add this to…" vs. "Create a new file for…" |
| Layout system | Flexbox, grid, absolute positioning, custom Stack component |
Notes
- The MCP server provides structured data; what the model does with it depends entirely on what you ask
- When output seems wrong, try being explicit about which tool to invoke (see Trigger Specific Tools)
- Reusable team guidelines belong in custom rules (see Add Custom Rules)
Related
- Trigger Specific Tools
- Add Custom Rules
- Structure Figma File
Write to Canvas
Enables AI agents to create and modify native Figma content (frames, components, variables, auto layout) directly on the canvas using the use_figma tool. Output is editable design structure, not static screenshots.
Signature / Usage
# Basic prompt pattern
"Using this Figma file: [URL], create a new page and build a settings screen with auto layout"
# From a selection link
"Using this selection: [link], convert these raw values to variables"
# Follow-up in the same file
"Add an empty state below that"Options / Props
| Requirement | Detail |
|---|---|
| Figma seat | Full seat required (Dev seats are read-only) |
| File permission | Edit permission on the target file |
| Server | Remote Figma MCP server must be configured |
| Supported clients | Claude Code, Claude Desktop, Cursor, VS Code, Copilot CLI, and others |
Notes
- Feature is beta-level quality and currently free; will become usage-based and paid after beta
- Response output limit: 20 KB per tool call
- No asset or image support in write operations
- Custom fonts not supported
- Components must be manually published before Code Connect integration works
- Workflow: system → canvas → code (not a screenshot, generates real Figma layer structure)
Related
- Remote Server Installation
- Tools and Prompts
- Code Connect Integration
- Write Effective Prompts
Data Types
TypeScript interface and union type definitions used throughout the Plugin API for type-checking and passing structured values.
Signature / Usage
// Color
interface RGB { readonly r: number; readonly g: number; readonly b: number }
interface RGBA { readonly r: number; readonly g: number; readonly b: number; readonly a: number }
// Paint union
type Paint = SolidPaint | GradientPaint | ImagePaint | VideoPaint | PatternPaint
// Effect union
type Effect = DropShadowEffect | InnerShadowEffect | BlurEffect |
NoiseEffect | TextureEffect | GlassEffect
// Transform (2×3 affine matrix)
type Transform = [[number, number, number], [number, number, number]]Options / Props
Color
RGB
interface RGB {
readonly r: number // 0–1
readonly g: number // 0–1
readonly b: number // 0–1
}RGBA
interface RGBA {
readonly r: number // 0–1
readonly g: number // 0–1
readonly b: number // 0–1
readonly a: number // 0–1 (opacity)
}Black: { r: 0, g: 0, b: 0, a: 1 } — White: { r: 1, g: 1, b: 1, a: 1 }
BlendMode
type BlendMode =
'PASS_THROUGH' | 'NORMAL' | 'DARKEN' | 'MULTIPLY' | 'LINEAR_BURN' |
'COLOR_BURN' | 'LIGHTEN' | 'SCREEN' | 'LINEAR_DODGE' | 'COLOR_DODGE' |
'OVERLAY' | 'SOFT_LIGHT' | 'HARD_LIGHT' | 'DIFFERENCE' | 'EXCLUSION' |
'HUE' | 'SATURATION' | 'COLOR' | 'LUMINOSITY'---
Paint
type Paint = SolidPaint | GradientPaint | ImagePaint | VideoPaint | PatternPaintCommon fields on all paints: visible?: boolean, opacity?: number, blendMode?: BlendMode
SolidPaint
| Field | Type | Description |
|---|---|---|
type | 'SOLID' | — |
color | RGB | Fill color |
boundVariables? | Record<string, VariableAlias> | Variable bindings |
GradientPaint
| Field | Type | Description |
|---|---|---|
type | `'GRADIENT_LINEAR' \ | 'GRADIENT_RADIAL' \ |
gradientTransform | Transform | Gradient positioning matrix |
gradientStops | ReadonlyArray<ColorStop> | Color positions |
ImagePaint
| Field | Type | Description |
|---|---|---|
type | 'IMAGE' | — |
scaleMode | `'FILL' \ | 'FIT' \ |
imageHash | `string \ | null` |
imageTransform? | Transform | Crop positioning |
scalingFactor? | number | Tile repetition |
rotation? | number | +90 increments |
filters? | ImageFilters | Exposure, contrast, etc. |
VideoPaint / PatternPaint
VideoPaint mirrors ImagePaint with type: 'VIDEO' and videoHash. PatternPaint references a source node with type: 'PATTERN' and sourceNodeId, tileType, scalingFactor, spacing.
---
Effect
type Effect = DropShadowEffect | InnerShadowEffect | BlurEffect |
NoiseEffect | TextureEffect | GlassEffectDropShadowEffect / InnerShadowEffect
| Field | Type | Description |
|---|---|---|
type | `'DROP_SHADOW' \ | 'INNER_SHADOW'` |
color | RGBA | Shadow color |
offset | Vector | X/Y displacement |
radius | number | Blur radius (≥ 0) |
spread? | number | Expansion/contraction |
visible | boolean | — |
blendMode | BlendMode | — |
showShadowBehindNode? | boolean | Drop shadow only |
BlurEffect
| Field | Type | Description |
|---|---|---|
type | `'LAYER_BLUR' \ | 'BACKGROUND_BLUR'` |
radius | number | Blur amount |
visible | boolean | — |
---
LayoutGrid
type LayoutGrid = RowsColsLayoutGrid | GridLayoutGridAlways check pattern before reading other properties.
RowsColsLayoutGrid
| Field | Type | Description |
|---|---|---|
pattern | `'ROWS' \ | 'COLUMNS'` |
alignment | `'MIN' \ | 'MAX' \ |
gutterSize | number | Space between sections |
count | number | Section count (Infinity for auto) |
sectionSize? | number | Individual section size |
offset? | number | Edge spacing |
GridLayoutGrid
| Field | Type | Description |
|---|---|---|
pattern | 'GRID' | — |
sectionSize | number | Cell size |
---
Transform
A 2×3 affine transformation matrix (top two rows of a 3×3 matrix):
type Transform = [
[number, number, number],
[number, number, number]
]
// Identity: [[1, 0, 0], [0, 1, 0]]
// Translation by (tx, ty): [[1, 0, tx], [0, 1, ty]]---
Vector and Rect
interface Vector { readonly x: number; readonly y: number }
interface Rect { readonly x: number; readonly y: number; readonly width: number; readonly height: number }---
Constraints
interface Constraints {
readonly horizontal: ConstraintType
readonly vertical: ConstraintType
}
type ConstraintType = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'SCALE'MIN = left/top, MAX = right/bottom, STRETCH = both sides, SCALE = proportional.
---
ExportSettings
type ExportSettings = ExportSettingsImage | ExportSettingsSVG | ExportSettingsPDF | ExportSettingsRESTCommon fields: contentsOnly?, useAbsoluteBounds?, suffix?, colorProfile?
| Subtype | format | Key fields |
|---|---|---|
ExportSettingsImage | `'PNG' \ | 'JPG'` |
ExportSettingsSVG | 'SVG' | svgOutlineText?, svgIdAttribute?, svgSimplifyStroke? |
ExportSettingsPDF | 'PDF' | — |
ExportSettingsREST | 'JSON_REST_V1' | REST API equivalent response |
---
Variable & VariableCollection
Variable
| Property | Type | Description |
|---|---|---|
id | string (readonly) | Unique ID |
name | string | Display name |
variableCollectionId | string (readonly) | Parent collection |
resolvedType | VariableResolvedDataType (readonly) | `'BOOLEAN' \ |
valuesByMode | Record<string, VariableValue> (readonly) | Values per mode |
remote | boolean (readonly) | From team library |
key | string (readonly) | Import key |
codeSyntax | Record<string, string> (readonly) | Platform code definitions |
Methods: setValueForMode(modeId, value), resolveForConsumer(consumer), remove(), getPublishStatusAsync(), setVariableCodeSyntax(platform, value), removeVariableCodeSyntax(platform)
---
Image
interface Image {
readonly hash: string
getBytesAsync(): Promise<Uint8Array>
getSizeAsync(): Promise<{ width: number; height: number }>
}Created via figma.createImage(data: Uint8Array) or figma.getImageByHash(hash). Max 4096×4096 px; PNG, JPEG, GIF supported.
---
FontName
interface FontName {
readonly family: string // e.g. 'Inter'
readonly style: string // e.g. 'Regular', 'Bold Italic'
}---
Guide
interface Guide {
readonly axis: 'X' | 'Y'
readonly offset: number
}---
Reaction, Action, Trigger
Prototype interaction types:
Reaction = { trigger: Trigger | null; action: Action | null }Trigger— user interaction (e.g. click, hover, key press)Action— navigation or overlay behavior
---
DocumentChange / NodeChange / StyleChange
Document change events deliver typed change descriptors:
DocumentChangeEvent.documentChanges: DocumentChange[]NodeChangeEvent.changedNode: SceneNodeStyleChangeEvent.changedStyle: BaseStyle
Notes
figma.mixed(unique symbol) is returned for node-level properties that differ across a mixed selection.- All numeric color channels are 0–1, not 0–255.
- Use
figma.util.rgb()/figma.util.rgba()/figma.util.solidPaint()for converting CSS color strings.
Related
- node-properties
- figma.util
- figma.variables
Editor Types
Figma plugins can target one or more editor environments. The active environment is exposed at runtime via figma.editorType.
Signature / Usage
// manifest.json
{
"editorType": ["figma", "dev"]
}// Runtime detection
if (figma.editorType === 'figma') {
// Design editor logic
} else if (figma.editorType === 'figjam') {
// FigJam whiteboard logic
}Options / Props
| Value | Description |
|---|---|
"figma" | Design editor — full node creation and manipulation APIs |
"figjam" | Whiteboarding tool — sticky notes, connectors, shapes with text |
"dev" | Dev Mode — inspect and annotation focus; `figma.mode === 'inspect' \ |
"slides" | Presentation editor — SlideNode, SlideRowNode, SlideGridNode APIs |
"buzz" | Buzz product |
Notes
"dev"and"figjam"cannot appear together in the sameeditorTypearray.- Certain APIs are editor-scoped: e.g.
figma.createSticky()is only available in FigJam;figma.createConnector()is FigJam-only. - Use
figma.editorTypeto branch behavior in multi-editor plugins. figma.modegives finer-grained context within an editor ('default','textreview','inspect','codegen','linkpreview','auth').
Related
- manifest
- figma global object
figma.annotations
Sub-API for managing annotation categories in the current file.
Signature / Usage
// List existing categories
const categories = await figma.annotations.getAnnotationCategoriesAsync();
// Add a new category
const category = await figma.annotations.addAnnotationCategoryAsync({
label: 'Accessibility',
color: 'RED',
});
// Retrieve by ID
const found = await figma.annotations.getAnnotationCategoryByIdAsync(category.id);Options / Props
Methods
| Name | Signature | Description |
|---|---|---|
getAnnotationCategoriesAsync() | () => Promise<AnnotationCategory[]> | All annotation categories in the current file |
getAnnotationCategoryByIdAsync() | `(id: string) => Promise<AnnotationCategory \ | null>` |
addAnnotationCategoryAsync() | (input: { label: string; color: AnnotationCategoryColor }) => Promise<AnnotationCategory> | Create a new annotation category |
Notes
AnnotationCategoryColoris an enum of preset color names (e.g.'RED','GREEN','BLUE').- Annotation categories are file-scoped — they appear in all pages of the document.
Related
- figma global object
- data-types
figma.clientStorage
Sub-API for persisting data locally on the user's machine. Data is scoped to the plugin ID and is not synced across users or devices.
Signature / Usage
// Store a value
await figma.clientStorage.setAsync('theme', 'dark');
// Retrieve a value
const theme = await figma.clientStorage.getAsync('theme');
// Delete a key
await figma.clientStorage.deleteAsync('theme');
// List all keys
const keys = await figma.clientStorage.keysAsync();Options / Props
Methods
| Name | Signature | Description |
|---|---|---|
getAsync() | `(key: string) => Promise<any \ | undefined>` |
setAsync() | (key: string, value: any) => Promise<void> | Store a value; rejects on failure |
deleteAsync() | (key: string) => Promise<void> | Remove a key; no-op if key doesn't exist |
keysAsync() | () => Promise<string[]> | List all stored keys |
Notes
- Storage capacity: 5 MB per plugin.
- Supported value types: objects, arrays, strings, numbers, booleans,
null,undefined,Uint8Array. - Data is isolated by plugin ID — different plugins cannot access each other's storage.
- Data is not synchronized across users or machines.
Related
- figma global object
figma.codegen
Sub-API for Dev Mode codegen plugins. Registers callbacks that fire when the user's selection changes in Dev Mode, producing code snippets displayed in the Inspect panel.
Signature / Usage
figma.codegen.on('generate', async (event: CodegenEvent) => {
const node = event.node;
return [
{
title: 'CSS',
code: `width: ${node.width}px;\nheight: ${node.height}px;`,
language: 'CSS',
},
];
});
figma.codegen.on('preferenceschange', async (event) => {
figma.codegen.refresh();
});Options / Props
Methods
| Name | Signature | Description |
|---|---|---|
on('generate', cb) | `(event: CodegenEvent) => Promise<CodegenResult[]> \ | CodegenResult[]` |
on('preferenceschange', cb) | (event: CodegenPreferencesEvent) => Promise<void> | Register callback for preference changes |
once(type, cb) | Same signatures as on() | Single-use callback |
off(type, cb) | Same signatures as on() | Remove callback |
refresh() | () => void | Re-trigger the generate callback |
Properties
| Name | Type | Description |
|---|---|---|
preferences | CodegenPreferences (readonly) | Current user-set preferences: unit, scaleFactor?, customSettings |
CodegenResult fields
| Name | Type | Description |
|---|---|---|
title | string | Section heading in the Inspect panel |
code | string | Code snippet content |
language | CodeLanguage | Syntax highlighting language |
Notes
- The
generatecallback has a 15-second timeout; return results before then. capabilities: ["codegen"]must be set inmanifest.json.figma.modewill be'codegen'when the codegen callback runs.CodegenPreferences.unitis'PIXEL'or'SCALED';scaleFactoris only present when'SCALED'.
Related
- figma global object
- editor-types
figma.constants
Sub-API exposing constant values such as FigJam color palettes.
Signature / Usage
// Access FigJam base color palette
const base = figma.constants.colors.figJamBase;
const baseLight = figma.constants.colors.figJamBaseLight;
// Use a color value
const hexColor = base['yellow']; // e.g. '#FFD966'Options / Props
Properties
| Name | Type | Description |
|---|---|---|
colors | ColorPalettes | Maps palette names to color-name-to-hex-code records |
ColorPalettes keys
| Key | Description |
|---|---|
figJamBase | FigJam base color palette |
figJamBaseLight | FigJam base light variant palette |
Notes
- The
colorsproperty is primarily useful in FigJam plugins when applying standard palette colors to sticky notes, shapes, and connectors. - Color values are hex strings (e.g.
'#FFD966').
Related
- figma global object
- data-types: ColorPalette
figma (Global Object)
The figma global object is the main entry point for all Plugin API operations. It provides access to the document tree, node creation, styles, events, and all sub-APIs.
Signature / Usage
// Access document root and current page
const page = figma.currentPage;
const doc = figma.root;
// Create nodes
const frame = figma.createFrame();
const text = figma.createText();
// Show UI
figma.showUI(__html__, { width: 300, height: 400 });
// Notify user
figma.notify('Done!');
// Close plugin
figma.closePlugin();Options / Props
Properties
| Name | Type | Description |
|---|---|---|
apiVersion | string | API version string |
command | string | Currently executing manifest command |
editorType | `'figma' \ | 'figjam' \ |
mode | `'default' \ | 'textreview' \ |
currentPage | PageNode | Visible page (settable) |
root | DocumentNode (readonly) | Document root |
mixed | unique symbol | Sentinel for mixed property values |
hasMissingFont | boolean | Whether document has missing fonts |
fileKey | `string \ | undefined` |
pluginId | `string \ | undefined` |
widgetId | `string \ | undefined` |
Core Methods
| Name | Signature | Description |
|---|---|---|
showUI() | (html: string, options?: ShowUIOptions) => void | Render iframe UI |
closePlugin() | (message?: string) => void | Terminate plugin |
notify() | (message: string, options?: NotificationOptions) => NotificationHandler | Toast notification |
commitUndo() | () => void | Commit current actions to undo history |
triggerUndo() | () => void | Trigger undo |
openExternal() | (url: string) => void | Open URL in browser |
Node Creation
| Method | Returns |
|---|---|
createRectangle() | RectangleNode |
createEllipse() | EllipseNode |
createPolygon() | PolygonNode |
createStar() | StarNode |
createVector() | VectorNode |
createText() | TextNode |
createFrame() | FrameNode |
createAutoLayout() | FrameNode (auto-layout enabled) |
createComponent() | ComponentNode (Design only) |
createPage() | PageNode (Design only) |
createSticky() | StickyNode (FigJam only) |
createTable() | TableNode (FigJam only) |
createConnector() | ConnectorNode (FigJam only) |
Boolean Operations
| Method | Returns |
|---|---|
union(nodes, parent, index?) | BooleanOperationNode |
subtract(nodes, parent, index?) | BooleanOperationNode |
intersect(nodes, parent, index?) | BooleanOperationNode |
exclude(nodes, parent, index?) | BooleanOperationNode |
flatten(nodes, parent?, index?) | VectorNode |
Node Query
| Method | Signature |
|---|---|
getNodeByIdAsync() | `(id: string) => Promise<BaseNode \ |
getNodeById() | `(id: string) => BaseNode \ |
Style Management
| Method | Returns |
|---|---|
createPaintStyle() | PaintStyle |
createTextStyle() | TextStyle |
createEffectStyle() | EffectStyle |
createGridStyle() | GridStyle |
getLocalPaintStylesAsync() | Promise<PaintStyle[]> |
getLocalTextStylesAsync() | Promise<TextStyle[]> |
getLocalEffectStylesAsync() | Promise<EffectStyle[]> |
getLocalGridStylesAsync() | Promise<GridStyle[]> |
Image / Font
| Method | Signature |
|---|---|
createImage() | (data: Uint8Array) => Image |
getImageByHash() | `(hash: string) => Image \ |
loadFontAsync() | (fontName: FontName) => Promise<void> |
listAvailableFontsAsync() | () => Promise<Font[]> |
Event Handling
| Method | Description |
|---|---|
on(type, callback) | Register event callback |
once(type, callback) | Single-use callback |
off(type, callback) | Remove callback |
Supported events: 'run', 'close', 'selectionchange', 'currentpagechange', 'documentchange', 'drop', 'nodechange', 'stylechange', 'canvasviewchange'
Sub-APIs
| Property | Description |
|---|---|
figma.ui | Iframe UI communication |
figma.util | Color/paint helpers |
figma.constants | FigJam color palettes |
figma.viewport | Canvas view control |
figma.clientStorage | Local persistent storage |
figma.variables | Variables and collections |
figma.codegen | Dev Mode codegen |
figma.payments | Payment flow |
figma.parameters | Quick-action parameters |
figma.textreview | Text review plugin lifecycle |
figma.timer | FigJam timer (FigJam only) |
figma.teamLibrary | Team library access |
figma.annotations | Annotation categories |
Notes
figma.mixedis returned by properties with inconsistent values across a mixed selection.- Always call
await figma.loadFontAsync(...)before modifyingTextNode.charactersor text style properties. - Prefer
getNodeByIdAsync()over the deprecated synchronousgetNodeById().
Related
- figma.ui
- figma.viewport
- figma.clientStorage
- figma.variables
- DocumentNode
- PageNode
figma.parameters
Sub-API for handling quick-action parameter input. Registers callbacks that fire on every keystroke to power autocomplete suggestions in the quick actions menu.
Signature / Usage
figma.parameters.on('input', ({ key, query, parameters, result }) => {
if (key === 'color') {
result.setSuggestions(['red', 'green', 'blue'].filter(c => c.startsWith(query)));
}
});
// Plugin runs after parameters are resolved; access via RunEvent
figma.on('run', ({ parameters }) => {
const color = parameters?.['color'];
});Options / Props
Methods on figma.parameters
| Name | Signature | Description |
|---|---|---|
on('input', cb) | (event: ParameterInputEvent) => void | Register handler; fires on every keystroke |
once('input', cb) | (event: ParameterInputEvent) => void | Single-use handler |
off('input', cb) | (event: ParameterInputEvent) => void | Remove handler |
ParameterInputEvent fields
| Name | Type | Description |
|---|---|---|
key | string | Parameter key from manifest |
query | string | Current user input string |
parameters | ParameterValues | Already-resolved earlier parameters |
result | SuggestionResults | Object used to push suggestions or errors |
SuggestionResults methods
| Name | Signature | Description |
|---|---|---|
setSuggestions() | `(suggestions: Array<string \ | SuggestionObject>) => void` |
setError() | (message: string) => void | Show error and block progression (not available with allowFreeform) |
setLoadingMessage() | (message: string) => void | Customize loading text while suggestions load |
SuggestionObject shape
| Name | Type | Description |
|---|---|---|
name | string | Display label (required) |
data | any | Hidden data returned when selected |
icon | `string \ | Uint8Array` |
iconUrl | string | URL-based icon |
Notes
manifest.jsonmust defineparametersentries withnameandkey.ParameterValuesresolved value priority:data→name→ string suggestion → freeform query →undefined(optional, skipped).setError()is unavailable whenallowFreeform: trueis set on the parameter.
Related
- manifest
- figma global object
figma.payments
Sub-API for gating plugin features behind a payment. Requires "payments" in the permissions array of manifest.json.
Signature / Usage
// Check payment status
if (figma.payments.status === 'UNPAID') {
// Show upsell prompt or initiate checkout
await figma.payments.initiateCheckoutAsync({ interstitial: 'PAID_FEATURE' });
}
// Generate a backend-verifiable token
const token = await figma.payments.getPluginPaymentTokenAsync();Options / Props
Properties
| Name | Type | Description |
|---|---|---|
status | `'UNPAID' \ | 'PAID' \ |
Methods
| Name | Signature | Description |
|---|---|---|
initiateCheckoutAsync() | `(options?: { interstitial?: 'PAID_FEATURE' \ | 'TRIAL_ENDED' \ |
getUserFirstRanSecondsAgo() | () => number | Seconds since user first ran the plugin (0 on first run / in development) |
getPluginPaymentTokenAsync() | () => Promise<string> | Secure token for backend payment verification |
requestCheckout() | () => void | Queue checkout for after text review mode exits |
setPaymentStatusInDevelopment() | (status: PaymentStatus) => void | Override status during local development only |
Notes
manifest.jsonmust include"permissions": ["payments"].initiateCheckoutAsyncthrows if called during query mode or widget rendering.setPaymentStatusInDevelopmentchanges apply globally to all locally-tested plugins and do not persist across client restarts.requestCheckout()is only for text review plugins.
Related
- manifest
- figma global object
figma.teamLibrary
Sub-API for accessing published library variables and collections. Requires "teamlibrary" in the permissions array of manifest.json.
Signature / Usage
// List all available library variable collections
const collections = await figma.teamLibrary.getAvailableLibraryVariableCollectionsAsync();
// Get variables inside a collection
for (const coll of collections) {
const vars = await figma.teamLibrary.getVariablesInLibraryCollectionAsync(coll.key);
// Import a specific variable
const imported = await figma.variables.importVariableByKeyAsync(vars[0].key);
}Options / Props
Methods
| Name | Signature | Description |
|---|---|---|
getAvailableLibraryVariableCollectionsAsync() | () => Promise<LibraryVariableCollection[]> | All variable collections from enabled libraries in the current file |
getVariablesInLibraryCollectionAsync() | (libraryCollectionKey: string) => Promise<LibraryVariable[]> | All variables inside a specific library collection |
Notes
manifest.jsonmust include"permissions": ["teamlibrary"].- Libraries must be manually enabled by the user via Figma's UI; the Plugin API cannot enable them programmatically.
LibraryVariableCollectionandLibraryVariableare descriptors only — to use a variable in the document, import it first viafigma.variables.importVariableByKeyAsync(key).- Promises reject if the collection doesn't exist, the user lacks access, or the request fails.
Related
- figma.variables
- manifest
figma.textreview
Sub-API for managing the text review plugin lifecycle. Requires "textreview" in the capabilities array of manifest.json.
Signature / Usage
// Request to be enabled as a text review plugin
try {
await figma.textreview.requestToBeEnabledAsync();
console.log('Text review enabled');
} catch {
console.log('User declined');
}
// Check status
if (figma.textreview.isEnabled) {
// Plugin is active for text review
}
// Disable
await figma.textreview.requestToBeDisabledAsync();Options / Props
Properties
| Name | Type | Description |
|---|---|---|
isEnabled | boolean (readonly) | Whether the plugin is currently enabled as a text review plugin |
Methods
| Name | Signature | Description |
|---|---|---|
requestToBeEnabledAsync() | () => Promise<void> | Show a user consent modal; resolves if accepted, rejects if cancelled |
requestToBeDisabledAsync() | () => Promise<void> | Disable text review; rejects if the plugin was not enabled |
Notes
manifest.jsonmust include"capabilities": ["textreview"].- Multiple cancellations in a single plugin run cause
requestToBeEnabledAsyncto auto-reject to prevent spam. figma.payments.requestCheckout()is available for gating text review behind payment.
Related
- manifest
- figma.payments
- figma global object
figma.timer
Sub-API for controlling the FigJam timer. Only available in FigJam documents.
Signature / Usage
// Start a 5-minute timer
figma.timer.start(300);
// Pause and resume
figma.timer.pause();
figma.timer.resume();
// Read state
console.log(figma.timer.state); // 'RUNNING' | 'PAUSED' | 'STOPPED'
console.log(figma.timer.remaining); // seconds leftOptions / Props
Properties
| Name | Type | Description |
|---|---|---|
remaining | number (readonly) | Seconds remaining; 0 if not started |
total | number (readonly) | Total duration in seconds; 0 if not started |
state | `'STOPPED' \ | 'PAUSED' \ |
Methods
| Name | Signature | Description |
|---|---|---|
start() | (seconds: number) => void | Start (or adjust) timer to the given duration; resumes if paused |
pause() | () => void | Pause; no-op if not running |
resume() | () => void | Resume; no-op if not paused |
stop() | () => void | Stop and reset; no-op if already stopped or finished |
Notes
- Only available in FigJam (
figma.editorType === 'figjam'); throws in other editors. - Calling
start()on a running timer adjusts the remaining time.
Related
- editor-types
- figma global object
figma.ui
Sub-API for managing the plugin's iframe UI — showing, hiding, resizing, repositioning, and passing messages between the plugin sandbox and the UI iframe.
Signature / Usage
// Show UI defined in manifest
figma.showUI(__html__, { width: 300, height: 400 });
// Send a message to the iframe
figma.ui.postMessage({ type: 'init', data: payload });
// Receive a message from the iframe
figma.ui.onmessage = (msg) => {
if (msg.type === 'resize') {
figma.ui.resize(msg.width, msg.height);
}
};
// Inside iframe (ui.html)
window.onmessage = (event) => {
const msg = event.data.pluginMessage;
// handle msg
};
parent.postMessage({ pluginMessage: { type: 'done' } }, '*');Options / Props
Methods
| Name | Signature | Description |
|---|---|---|
show() | () => void | Make UI visible (if created with visible: false) |
hide() | () => void | Hide UI; plugin code keeps running |
resize() | (width: number, height: number) => void | Resize UI (minimum 70×0) |
reposition() | (x: number, y: number) => void | Move UI position after creation |
getPosition() | () => { windowSpace: Vector; canvasSpace: Vector } | Get current UI position |
close() | () => void | Destroy iframe and UI |
postMessage() | (pluginMessage: any, options?: UIPostMessageOptions) => void | Send message to iframe |
on() | (type: 'message', callback: MessageEventHandler) => void | Register message handler |
once() | (type: 'message', callback: MessageEventHandler) => void | Single-use message handler |
off() | (type: 'message', callback: MessageEventHandler) => void | Remove message handler |
Properties
| Name | Type | Description |
|---|---|---|
onmessage | `MessageEventHandler \ | undefined` |
ShowUIOptions (passed to figma.showUI())
| Name | Type | Description |
|---|---|---|
visible | boolean | Whether to show immediately (default true) |
width | number | Initial width in px |
height | number | Initial height in px |
position | { x: number; y: number } | Initial screen position |
title | string | Window title |
themeColors | boolean | Pass Figma theme CSS variables to iframe |
Notes
- Messages flow from plugin sandbox → iframe via
figma.ui.postMessage(), and from iframe → sandbox viaparent.postMessage({ pluginMessage: ... }, '*'). - Use
figma.ui.onmessageorfigma.ui.on('message', cb)— they are equivalent. - The UI iframe has no direct access to the Figma document; all document operations must be relayed through messaging.
Related
- figma global object
- global fetch
figma.util
Sub-API providing convenience helpers for creating colors and paints from common encodings, and for normalizing markdown strings.
Signature / Usage
// Parse a CSS color string to RGB
const red = figma.util.rgb('#FF0000');
// Create a SolidPaint from a hex color
node.fills = [figma.util.solidPaint('#0078FF')];
// Update fill hue while keeping other paint properties
const updatedFill = figma.util.solidPaint('#FF00FF88', node.fills[0] as SolidPaint);
// Normalize markdown for Figma rich-text fields
const md = figma.util.normalizeMarkdown('# Title\n**Bold**');
component.descriptionMarkdown = md;Options / Props
Methods
| Name | Signature | Description |
|---|---|---|
rgb() | `(color: string \ | RGB \ |
rgba() | `(color: string \ | RGB \ |
solidPaint() | `(color: string \ | RGB \ |
normalizeMarkdown() | (markdown: string) => string | Normalize markdown to match what Figma's rich-text editors will render |
Notes
rgb()andrgba()accept CSS strings: hex (#RGB,#RRGGBB,#RRGGBBAA),rgb(),hsl(),lab(), named colors.solidPaint()is especially useful for updating a fill's color while preservingblendMode,opacity, etc.normalizeMarkdown()should be used before assigning todescriptionMarkdownto avoid unexpected rendering.
Related
- data-types: Paint
- figma global object
figma.variables
Sub-API for creating and managing Variables and VariableCollections — Figma's design token system.
Signature / Usage
// Create a collection and a color variable
const collection = figma.variables.createVariableCollection('Brand');
const colorVar = figma.variables.createVariable('primary', collection, 'COLOR');
// Set value for a mode
colorVar.setValueForMode(collection.defaultModeId, { r: 0, g: 0.47, b: 1, a: 1 });
// Bind to a node fill
const paint = figma.util.solidPaint('#0078FF');
const bound = figma.variables.setBoundVariableForPaint(paint, 'color', colorVar);
node.fills = [bound];
// Import from library
const imported = await figma.variables.importVariableByKeyAsync(key);Options / Props
Retrieval Methods
| Name | Signature | Description |
|---|---|---|
getVariableByIdAsync() | `(id: string) => Promise<Variable \ | null>` |
getVariableCollectionByIdAsync() | `(id: string) => Promise<VariableCollection \ | null>` |
getLocalVariablesAsync() | (type?: VariableResolvedDataType) => Promise<Variable[]> | All local variables, optionally filtered by type |
getLocalVariableCollectionsAsync() | () => Promise<VariableCollection[]> | All local collections |
Creation Methods
| Name | Signature | Description |
|---|---|---|
createVariable() | (name, collection, resolvedType) => Variable | Create a new variable inside a collection |
createVariableCollection() | (name: string) => VariableCollection | Create a new collection |
extendLibraryCollectionByKeyAsync() | (collectionKey, name) => Promise<ExtendedVariableCollection> | Extend a library collection locally |
Alias / Binding Methods
| Name | Signature | Description |
|---|---|---|
createVariableAlias() | (variable) => VariableAlias | Create an alias referencing another variable |
createVariableAliasByIdAsync() | (variableId) => Promise<VariableAlias> | Async version using variable ID |
setBoundVariableForPaint() | `(paint, field, variable \ | null) => SolidPaint` |
setBoundVariableForEffect() | `(effect, field, variable \ | null) => Effect` |
setBoundVariableForLayoutGrid() | `(grid, field, variable \ | null) => LayoutGrid` |
Library
| Name | Signature | Description |
|---|---|---|
importVariableByKeyAsync() | (key: string) => Promise<Variable> | Load a published variable from team library |
Notes
- Synchronous variants (
getVariableById,getLocalVariables, etc.) are deprecated; they throw whendocumentAccess: "dynamic-page"is set. - Passing
nullas thevariableargument to binding helpers unbinds the field. VariableResolvedDataTypevalues:'BOOLEAN','COLOR','FLOAT','STRING'.
Related
- figma.teamLibrary
- data-types: Variable
- node-properties: boundVariables
figma.viewport
Sub-API for reading and controlling the visible canvas area — scroll position, zoom level, and view bounds.
Signature / Usage
// Pan to center on a node
figma.viewport.scrollAndZoomIntoView([node]);
// Read current state
console.log(figma.viewport.center); // { x: 0, y: 0 }
console.log(figma.viewport.zoom); // 1.0 = 100%
// Set zoom and center
figma.viewport.zoom = 2;
figma.viewport.center = { x: 100, y: 200 };Options / Props
Properties
| Name | Type | Description |
|---|---|---|
center | Vector (read/write) | Center point of the visible canvas area |
zoom | number (read/write) | Zoom level — 1.0 = 100%, 0.5 = 50% |
bounds | Rect (readonly) | Full bounds of the visible viewport on the canvas |
slidesView | `'grid' \ | 'single-slide'` |
canvasView | `'grid' \ | 'single-asset'` |
Methods
| Name | Signature | Description |
|---|---|---|
scrollAndZoomIntoView() | (nodes: ReadonlyArray<BaseNode>) => void | Pan and zoom so all provided nodes are visible (equivalent to Shift+1) |
Notes
boundsis computed fromcenterandzoom; it reflects exactly what is on-screen.scrollAndZoomIntoView()does not animate; the viewport snaps immediately.
Related
- figma global object
global fetch()
A network fetch function available in the plugin sandbox (not in the UI iframe). Functionally similar to the browser fetch API but with Figma-specific constraints.
Signature / Usage
// Declare allowed domains in manifest.json first:
// "networkAccess": { "allowedDomains": ["api.example.com"] }
const response = await fetch('https://api.example.com/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' }),
});
if (response.ok) {
const data = await response.json();
}Options / Props
Function Signature
fetch(url: string, init?: FetchOptions): Promise<FetchResponse>FetchOptions
| Name | Type | Description |
|---|---|---|
method | string | HTTP verb: 'GET', 'POST', etc. |
headers | Record<string, string> | Request headers as a plain object |
body | `string \ | Uint8Array` |
cache | string | Cache control |
redirect | string | Redirect handling |
referrer | string | Referrer URL |
integrity | string | Subresource integrity |
FetchResponse
| Property/Method | Type | Description |
|---|---|---|
ok | boolean | true if status 200–299 |
status | number | HTTP status code |
statusText | string | Status message |
url | string | Final URL after redirects |
redirected | boolean | Whether a redirect occurred |
type | string | Response type |
headersObject | Record<string, string> | Response headers as plain object |
text() | () => Promise<string> | Body as text |
json() | () => Promise<any> | Body parsed as JSON |
arrayBuffer() | () => Promise<ArrayBuffer> | Body as ArrayBuffer |
Notes
- The
urlparameter must be a string —Requestobjects are not supported. - Headers are plain objects, not
Headersinstances (unlike browserfetch). - All requested domains must be listed in
manifest.jsonundernetworkAccess.allowedDomains. Requests to unlisted domains will fail. fetch()is only available in the plugin sandbox (themaincode). The UI iframe has access to the standard browserfetch.
Related
- manifest
- figma.ui
Plugin Manifest
The manifest.json file is required for every Figma plugin. It defines plugin identity, target editors, entry points, and declared capabilities.
Signature / Usage
{
"name": "MyPlugin",
"id": "737805260747778092",
"api": "1.0.0",
"editorType": ["figma"],
"main": "code.js",
"ui": "ui.html"
}Options / Props
Required fields
| Name | Type | Description |
|---|---|---|
name | string | Plugin name as displayed in the menu |
id | string | Unique identifier assigned by Figma (for publishing) |
api | string | Figma API version used (e.g. "1.0.0") |
main | string | File path to the plugin's JavaScript entry point |
editorType | array | Target editors: "figma", "figjam", "dev", "slides", "buzz" |
Optional fields
| Name | Type | Description |
|---|---|---|
ui | `string \ | object` |
documentAccess | string | Set "dynamic-page" to enable dynamic page loading (required for new plugins) |
networkAccess | object | { allowedDomains, reasoning?, devAllowedDomains? } — allowed fetch domains |
parameters | array | Quick-action parameters with name, key, description?, allowFreeform?, optional? |
parameterOnly | boolean | Require parameter entry before plugin launches (default true) |
menu | array | Submenu structure with items, separators, and nested submenus |
relaunchButtons | array | Relaunch button config: { command, name, multipleSelection? } |
permissions | array | Access levels: "currentuser", "activeusers", "fileusers", "payments", "teamlibrary" |
capabilities | array | Features: "textreview", "codegen", "inspect", "vscode" |
codegenLanguages | array | Code languages supported by codegen plugins |
codegenPreferences | array | Codegen preference definitions (units, selections, actions) |
enableProposedApi | boolean | Development-only flag for experimental APIs |
enablePrivatePluginApi | boolean | Enable private plugin-specific APIs |
build | string | Shell command to run before loading files |
Notes
idis generated by Figma when you first register a plugin; leave it blank during local dev then fill it in before publishing.devandfigjamcannot be combined in the sameeditorTypearray.networkAccess.allowedDomainsmust list every domain your plugin calls viafetch().- Setting
documentAccess: "dynamic-page"disables all deprecated synchronous node/variable APIs.
Related
- figma global object
- figma.parameters
- editor-types
BooleanOperationNode
A node that combines child shapes using a boolean set operation (union, subtract, intersect, or exclude).
Signature / Usage
// Create boolean operations
const union = figma.union([rect, ellipse], figma.currentPage);
const subtract = figma.subtract([rect, ellipse], figma.currentPage);
const intersect = figma.intersect([rect, ellipse], figma.currentPage);
const exclude = figma.exclude([rect, ellipse], figma.currentPage);
// Inspect
console.log(union.booleanOperation); // 'UNION'Options / Props
Properties
| Name | Type | Description |
|---|---|---|
type | 'BOOLEAN_OPERATION' (readonly) | Node type identifier |
booleanOperation | `'UNION' \ | 'INTERSECT' \ |
children | ReadonlyArray<SceneNode> (readonly) | Shapes being combined |
expanded | boolean | Expanded state in layers panel |
fills | ReadonlyArray<Paint> | Fill paints on the result |
strokes | ReadonlyArray<Paint> | Stroke paints |
effects | ReadonlyArray<Effect> | Shadow/blur effects |
Methods
| Name | Description |
|---|---|
clone() | Duplicate the boolean operation node |
Notes
- Like
GroupNode, a boolean operation node auto-resizes to fit its children. - Created via
figma.union(),figma.subtract(),figma.intersect(),figma.exclude(). - Use
figma.flatten()to merge a boolean operation into a singleVectorNode.
Related
- VectorNode
- GroupNode
ComponentSetNode
A container for component variants. All direct children must be ComponentNode objects. Behaves like a frame, but is variant-aware.
Signature / Usage
// ComponentSetNode is typically created by Figma when you combine components as variants
// Accessing an existing component set:
const set = figma.currentPage.findOne(n => n.type === 'COMPONENT_SET') as ComponentSetNode;
console.log(set.defaultVariant.name);
console.log(set.componentPropertyDefinitions);Options / Props
Properties
| Name | Type | Description |
|---|---|---|
type | 'COMPONENT_SET' (readonly) | Node type identifier |
defaultVariant | ComponentNode (readonly) | Top-left-most variant spatially |
children | ReadonlyArray<SceneNode> (readonly) | All child component nodes |
componentPropertyDefinitions | ComponentPropertyDefinitions (readonly) | All variant properties and options |
description | string | Plain-text annotation |
descriptionMarkdown | string | Markdown annotation |
documentationLinks | DocumentationLink[] | Reference links |
remote | boolean (readonly) | Whether from team library |
key | string (readonly) | Key for importing |
Methods
| Name | Signature | Description |
|---|---|---|
clone() | () => ComponentSetNode | Duplicate as new components with no instances |
addComponentProperty() | (name, type, defaultValue) => string | Add BOOLEAN, TEXT, INSTANCE_SWAP, VARIANT, or SLOT property |
editComponentProperty() | (name, newValue) => string | Modify existing property |
deleteComponentProperty() | (name) => void | Remove property |
getPublishStatusAsync() | () => Promise<PublishStatus> | Check library status |
Notes
- A component set with no children deletes itself.
- Variant properties define dimensions like
"Size"or"State"with enumerated values. defaultVariantis used as the preview and initial instance when dragging from the assets panel.
Related
- ComponentNode
- InstanceNode
ComponentNode
A reusable UI element. Behaves like a FrameNode but can produce auto-updating instances. Only available in the Design editor.
Signature / Usage
const component = figma.createComponent();
component.name = 'Button';
component.resize(120, 40);
// Add a component property
component.addComponentProperty('Label', 'TEXT', 'Click me');
// Create an instance
const instance = component.createInstance();
instance.x = 200;
// Find all instances in the document
const instances = await component.getInstancesAsync();Options / Props
Properties
| Name | Type | Description |
|---|---|---|
type | 'COMPONENT' (readonly) | Node type identifier |
componentPropertyDefinitions | ComponentPropertyDefinitions (readonly) | All defined properties and defaults |
description | string | Plain-text annotation |
descriptionMarkdown | string | Markdown annotation |
documentationLinks | DocumentationLink[] | Reference links |
remote | boolean (readonly) | Whether from a team library |
key | string (readonly) | Key for importing published component |
Methods
| Name | Signature | Description |
|---|---|---|
createInstance() | () => InstanceNode | Create an instance of this component |
createSlot() | () => SlotNode | Add a slot node within the component |
getInstancesAsync() | () => Promise<InstanceNode[]> | All instances in the document |
addComponentProperty() | (name, type, defaultValue) => string | Add property (BOOLEAN, TEXT, INSTANCE_SWAP, VARIANT, SLOT); returns unique prop name |
editComponentProperty() | (name, newValue) => string | Modify property; returns updated name |
deleteComponentProperty() | (name) => void | Remove property |
getPublishStatusAsync() | () => Promise<PublishStatus> | Check library publication status |
clone() | () => ComponentNode | Duplicate (no instances transferred) |
Notes
ComponentNodeinherits allFrameNodelayout, geometry, and prototyping properties.- Property names returned by
addComponentProperty()are unique; store the returned value for future edits. - A component set (
ComponentSetNode) is needed for variant support.
Related
- ComponentSetNode
- InstanceNode
- FrameNode
DocumentNode
The root node of the Figma document. There is exactly one DocumentNode per browser tab. Its children must be PageNode objects.
Signature / Usage
const doc = figma.root; // DocumentNode
// Iterate pages
for (const page of doc.children) {
console.log(page.name);
}
// Search entire document
const allTexts = doc.findAll(n => n.type === 'TEXT');Options / Props
Properties
| Name | Type | Description |
|---|---|---|
type | 'DOCUMENT' (readonly) | Node type identifier |
children | ReadonlyArray<PageNode> (readonly) | Pages in the document |
documentColorProfile | `'LEGACY' \ | 'SRGB' \ |
id | string (readonly) | Node ID |
name | string | Document name |
Methods
| Name | Signature | Description |
|---|---|---|
appendChild() | (child: PageNode) => void | Add a page at the end |
insertChild() | (index: number, child: PageNode) => void | Insert a page at position |
findChildren() | (cb?) => PageNode[] | Search immediate children |
findChild() | `(cb) => PageNode \ | null` |
findAll() | (cb?) => SceneNode[] | Search entire document tree |
findOne() | `(cb) => SceneNode \ | null` |
findAllWithCriteria() | (criteria: FindAllCriteria) => NodeType[] | Typed search across document |
findWidgetNodesByWidgetId() | (widgetId: string) => WidgetNode[] | Find widgets by ID |
Notes
figma.rootalways points to theDocumentNode.- Only
PageNodeobjects can be direct children. documentColorProfileis read-only; it reflects the file's color space setting.
Related
- PageNode
- figma global object
FrameNode
A container that defines layout hierarchy — analogous to <div> in HTML. Supports auto-layout, CSS grid layout, and prototyping reactions.
Signature / Usage
const frame = figma.createFrame();
frame.name = 'Card';
frame.resize(320, 200);
// Enable auto-layout
frame.layoutMode = 'HORIZONTAL';
frame.itemSpacing = 16;
frame.paddingLeft = 24;
frame.paddingRight = 24;
// Add children
const rect = figma.createRectangle();
frame.appendChild(rect);Options / Props
Type
| Name | Type | Description |
|---|---|---|
type | 'FRAME' (readonly) | Node type identifier |
Layout
| Name | Type | Description |
|---|---|---|
layoutMode | `'NONE' \ | 'HORIZONTAL' \ |
layoutWrap | `'NO_WRAP' \ | 'WRAP'` |
primaryAxisSizingMode | `'FIXED' \ | 'AUTO'` |
counterAxisSizingMode | `'FIXED' \ | 'AUTO'` |
primaryAxisAlignItems | `'MIN' \ | 'CENTER' \ |
counterAxisAlignItems | `'MIN' \ | 'CENTER' \ |
counterAxisAlignContent | `'AUTO' \ | 'SPACE_BETWEEN'` |
itemSpacing | number | Gap between items |
counterAxisSpacing | `number \ | null` |
paddingTop/Bottom/Left/Right | number | Inner padding |
clipsContent | boolean | Clip children to frame bounds |
overflowDirection | OverflowDirection | Scrolling direction |
Grid Layout
| Name | Type | Description |
|---|---|---|
gridRowCount | `number \ | null` |
gridColumnCount | `number \ | null` |
gridRowGap | number | Row gap |
gridColumnGap | number | Column gap |
Geometry
| Name | Type | Description |
|---|---|---|
fills | ReadonlyArray<Paint> | Background fills |
strokes | ReadonlyArray<Paint> | Border strokes |
strokeWeight | number | Stroke weight |
cornerRadius | `number \ | typeof figma.mixed` |
topLeftRadius / topRightRadius / bottomLeftRadius / bottomRightRadius | number | Per-corner radii |
effects | ReadonlyArray<Effect> | Shadow and blur effects |
Prototyping
| Name | Type | Description |
|---|---|---|
reactions | ReadonlyArray<Reaction> | Prototype interactions |
numberOfFixedChildren | number | Count of fixed scroll-pinned children |
Methods
| Name | Description |
|---|---|
clone() | Duplicate the frame |
appendChild(child) | Add a child node |
insertChild(index, child) | Insert at position |
findAll(cb?) | Search descendants |
findOne(cb) | First matching descendant |
resize(w, h) | Resize frame |
resizeWithoutConstraints(w, h) | Resize ignoring child constraints |
getTopLevelFrame() | Nearest ancestor frame |
Notes
layoutMode = 'NONE'means absolute positioning; children usex/yfor placement.- Frames persist their size when children are removed (unlike
GroupNode). - Use
createAutoLayout()for a pre-configured horizontal auto-layout frame.
Related
- GroupNode
- ComponentNode
- InstanceNode
- node-properties
GroupNode
A semantic grouping container. Unlike FrameNode, a group auto-resizes to fit its children and does not establish layout boundaries.
Signature / Usage
// Groups are typically created by the user; plugins create them via:
const group = figma.group([rect, ellipse], figma.currentPage);
group.name = 'Icons';Options / Props
Properties
| Name | Type | Description |
|---|---|---|
type | 'GROUP' (readonly) | Node type identifier |
children | ReadonlyArray<SceneNode> (readonly) | Child nodes |
expanded | boolean | Whether expanded in layers panel |
x, y | number | Position (auto-computed from children bounds) |
width, height | number (readonly) | Size (auto-computed from children bounds) |
opacity | number | 0–1 |
blendMode | BlendMode | Blend mode |
visible | boolean | Visibility |
locked | boolean | Lock state |
Methods
| Name | Description |
|---|---|
clone() | Duplicate the group |
appendChild(child) | Add a child node |
insertChild(index, child) | Insert at position |
findAll(cb?) | Search descendants |
findOne(cb) | First matching descendant |
Notes
- A group with no children deletes itself automatically.
- Position and size always reflect bounding box of children; setting
x/ytranslates the group. - Do not assume a node type is stable during long-running operations — users can convert frames to groups via the UI.
Related
- FrameNode
- BooleanOperationNode
InstanceNode
A copy of a ComponentNode that auto-updates when the component changes. Created via component.createInstance().
Signature / Usage
const instance = component.createInstance();
instance.x = 100;
instance.y = 100;
// Set component property values
instance.setProperties({ 'Label#abc123': 'Submit' });
// Swap to a different component
instance.swapComponent(otherComponent);
// Detach from component (becomes a plain FrameNode)
const frame = instance.detachInstance();Options / Props
Properties
| Name | Type | Description |
|---|---|---|
type | 'INSTANCE' (readonly) | Node type identifier |
mainComponent | `ComponentNode \ | null` |
componentProperties | ComponentProperties (readonly) | Current property values |
scaleFactor | number | Scale applied to the instance |
exposedInstances | InstanceNode[] (readonly) | Nested instances exposed to this level |
isExposedInstance | boolean | Whether marked as exposed |
overrides | object[] (readonly) | Directly overridden fields on this instance |
Methods
| Name | Signature | Description |
|---|---|---|
clone() | () => InstanceNode | Duplicate the instance |
getMainComponentAsync() | `() => Promise<ComponentNode \ | null>` |
swapComponent() | (component: ComponentNode) => void | Swap source component, preserving overrides where possible |
setProperties() | (properties: Record<string, any>) => void | Set component property values |
detachInstance() | () => FrameNode | Convert to a regular frame |
removeOverrides() | () => void | Remove all direct overrides |
Notes
mainComponentcan benullwhen the source component lives in a remote library not yet loaded — usegetMainComponentAsync()instead.- Property keys in
setProperties()use the format"propName#uniqueId"as returned byaddComponentProperty(). detachInstance()is irreversible.
Related
- ComponentNode
- ComponentSetNode
- FrameNode
Other Node Types
Reference for less commonly used node types: SliceNode, EmbedNode, LinkUnfurlNode, MediaNode, TableNode, TableCellNode, WidgetNode, CodeBlockNode, RemovedNode, HighlightNode, ShapeWithTextNode, StampNode, WashiTapeNode, TextPathNode, TransformGroupNode, InteractiveSlideElementNode, and SlotNode.
SliceNode (type: 'SLICE')
Defines an export region on the canvas. Does not render visually.
const slice = figma.createSlice();
slice.resize(200, 100);
slice.exportSettings = [{ format: 'PNG', constraint: { type: 'SCALE', value: 2 } }];---
EmbedNode (type: 'EMBED')
An embedded external content node (e.g. a Loom video embed in FigJam).
| Property | Type | Description |
|---|---|---|
embedData | EmbedData (readonly) | Source URL and metadata |
---
LinkUnfurlNode (type: 'LINK_UNFURL')
An unfurled link preview card in FigJam.
| Property | Type | Description |
|---|---|---|
linkUnfurlData | LinkUnfurlData (readonly) | URL and preview metadata |
---
MediaNode (type: 'MEDIA')
A video or GIF node. Only in FigJam.
| Property | Type | Description |
|---|---|---|
mediaData | MediaData (readonly) | Media source information |
---
TableNode (type: 'TABLE') and TableCellNode (type: 'TABLE_CELL')
A table in FigJam. Created via figma.createTable().
const table = figma.createTable(3, 4); // 3 rows, 4 columns
const cell = table.cellAt(0, 0) as TableCellNode;| Property | Type | Description |
|---|---|---|
numRows | number (readonly) | Row count |
numColumns | number (readonly) | Column count |
TableCellNode inherits text and fill properties.
---
WidgetNode (type: 'WIDGET')
A FigJam widget. Read-only from a plugin context.
| Property | Type | Description |
|---|---|---|
widgetId | string (readonly) | Widget definition ID |
widgetSyncedState | Record<string, any> (readonly) | Widget state snapshot |
---
CodeBlockNode (type: 'CODE_BLOCK')
A code block sticky in FigJam.
| Property | Type | Description |
|---|---|---|
code | string | Code content |
codeLanguage | CodeLanguage | Syntax highlighting language |
---
RemovedNode
Returned by some APIs when a node has been deleted. Check node.removed === true before use.
| Property | Type | Description |
|---|---|---|
removed | true (readonly) | Always true for removed nodes |
---
HighlightNode (type: 'HIGHLIGHT')
A highlight annotation node (FigJam). Created by users on top of other content.
---
ShapeWithTextNode (type: 'SHAPE_WITH_TEXT')
A FigJam shape that contains text (e.g. rounded rectangle with label). Has a text sublayer property for accessing the text content.
| Property | Type | Description |
|---|---|---|
shapeType | ShapeType | The shape variant (e.g. 'SQUARE', 'ELLIPSE', 'DIAMOND', etc.) |
text | TextSublayerNode (readonly) | Text sublayer |
---
StampNode (type: 'STAMP')
A reaction stamp in FigJam (emoji reaction).
---
WashiTapeNode (type: 'WASHI_TAPE')
A decorative washi tape strip in FigJam.
---
TextPathNode (type: 'TEXT_PATH')
Text that follows a vector path.
| Property | Type | Description |
|---|---|---|
textPathData | TextPathStartData | Path start position and offset |
---
TransformGroupNode (type: 'TRANSFORM_GROUP')
A group node created by certain transform operations. Behaves similarly to GroupNode.
---
InteractiveSlideElementNode (type: 'INTERACTIVE_SLIDE_ELEMENT')
An interactive element within a Figma Slides presentation (e.g. a poll or quiz component).
---
SlotNode (type: 'SLOT')
A slot placeholder within a component, used with slot-based component properties. Created via component.createSlot().
Notes
EmbedNode,LinkUnfurlNode,MediaNode,TableNode,WidgetNode, andCodeBlockNodeare FigJam-only.SliceNodeis Design-only; it has no visual representation.- Always check
node.removedbefore operating on nodes obtained from long-lived references.
Related
- editor-types
- node-properties
Errors
Standard HTTP error codes returned by the Figma REST API.
Options / Props
| Status Code | Name | Description |
|---|---|---|
400 | Bad Request | Parameters are invalid or malformed. Also occurs when requested resources are too large, causing a timeout. Reduce the quantity and size of objects in the request. |
403 | Forbidden | The request was valid, but the server refused the action. Typically caused by insufficient permissions or unencrypted HTTP (use HTTPS). |
404 | Not Found | The requested file or resource was not found, or is inaccessible to the current user. |
429 | Too Many Requests | API rate limit exceeded. Check Retry-After header and wait before retrying. |
500 | Internal Server Error | Most commonly occurs for very large image render requests that time out. Reduce the number and size of objects. |
Notes
- All requests must use HTTPS; plain HTTP returns 403
- For 429 responses, use the
Retry-Afterresponse header value (seconds to wait) - 400 and 500 errors caused by large payloads can be resolved by splitting requests into smaller batches
- API usage is governed by Figma's Terms of Service; Figma may deny API access
Related
- Rate Limits
- Files