Skip to content

How to Create a ComfyUI Custom Node (2026): Step-by-Step Python Tutorial

8–11 minutes
Woman in a sunny cafe holding a tablet with a CUSTOM NODE card, hook build your own node

Every ComfyUI custom node you install, from upscalers to face detailers, is just a small Python class in a folder. Once you see the pattern, writing your own takes about 15 minutes. You can wrap a script you already use, add a missing utility, or share a tool with the community.

This tutorial builds a working node from scratch.

You will scaffold a project with comfy-cli, write the Python class, register it, add a dropdown option, send a message to the browser with a small JavaScript extension, then convert it to the new V3 schema and publish it to the Comfy Registry.

It follows the official ComfyUI documentation as of December 2026 and assumes only basic Python.

TL;DR

  • Scaffold: cd ComfyUI/custom_nodes then comfy node scaffold.
  • V1 node needs: CATEGORY, INPUT_TYPES, RETURN_TYPES and FUNCTION, plus an entry in NODE_CLASS_MAPPINGS.
  • Images are torch.Tensor batches shaped [B,H,W,C]; always return a tuple like (result,).
  • Restart ComfyUI after every Python change.
  • New nodes: use the V3 schema (io.ComfyNode, define_schema, execute, comfy_entrypoint); new features land only in V3.
  • Publish: comfy node init, then comfy node publish with a Registry API key.

How Custom Nodes Work

ComfyUI runs as a client and a server. The Python server does the real work: loading models, running diffusion and processing images. The JavaScript client in your browser draws the graph and widgets.

A custom node can live on either side, or both:

Type What it does Example
Server side only A Python class with inputs, outputs and a function. Most nodes are this type. Image invert, resize, prompt tools
Client side only Changes the UI without adding processing Themes, menu tweaks
Independent client and server Python node plus a related UI widget, talking through normal data flow A node with a custom preview widget
Connected client and server UI and server talk directly Live interactive editors

One warning from the docs: nodes that need direct client-server messages do not work when a workflow runs through the API. Keep core logic in Python if you plan to run workflows headless, as in our ComfyUI API Python guide.

When ComfyUI starts, it imports every folder in custom_nodes that has an __init__.py, and reads NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS and WEB_DIRECTORY from it. That is the whole loading mechanism.

Prerequisites

  • A working ComfyUI install. The docs recommend a manual (git) install for development; see our ComfyUI beginner guide.
  • comfy-cli installed (pip install comfy-cli), covered in our comfy-cli guide.
  • Git, a code editor, and basic Python.

Scaffold the Project

  1. Go to your custom nodes folder:
    cd ComfyUI/custom_nodes
  2. Run the scaffold command:
    comfy node scaffold
  3. Answer the prompts. It asks for your name, email, GitHub username, project name (for example FirstComfyNode), a short description, version, licence, and whether to include a web directory for custom JavaScript. Answer y to the last one so you can follow the JavaScript section.
  4. Open the new folder. The scaffold uses the official cookiecutter-comfy-extension template and creates a git repository with src/nodes.py and an example node already in place.

Prefer to start by hand? Any folder in custom_nodes with an __init__.py that exports NODE_CLASS_MAPPINGS works. The scaffold just saves time and adds packaging files you need later.

Write the Node Class

Our example takes a batch of images and returns the brightest one. Add this to the end of src/nodes.py:

import torch

class ImageSelector:
    CATEGORY = "example"

    @classmethod
    def INPUT_TYPES(s):
        return {"required": {"images": ("IMAGE",)}}

    RETURN_TYPES = ("IMAGE",)
    FUNCTION = "choose_image"

    def choose_image(self, images):
        brightness = list(torch.mean(image.flatten()).item() for image in images)
        brightest = brightness.index(max(brightness))
        result = images[brightest].unsqueeze(0)
        return (result,)

Every V1 node needs these four parts:

Part Purpose
CATEGORY Where the node appears in the Add Node menu
INPUT_TYPES Class method returning the inputs, grouped as required, optional or hidden
RETURN_TYPES Tuple of output types
FUNCTION Name of the method ComfyUI calls to run the node

Two details trip up beginners:

  • IMAGE always means a batch. The tensor shape is [B,H,W,C]: batch, height, width and 3 colour channels. A single image is a batch of 1. That is why the code calls unsqueeze(0) to turn one [H,W,C] image back into a [1,H,W,C] batch.
  • Return a tuple. The trailing comma in return (result,) is essential. Without it Python returns a bare tensor and the node fails.

Register the Node

ComfyUI only sees nodes listed in NODE_CLASS_MAPPINGS. Update the mappings at the end of src/nodes.py:

NODE_CLASS_MAPPINGS = {
    "Example": Example,
    "Image Selector": ImageSelector,
}

NODE_DISPLAY_NAME_MAPPINGS = {
    "Example": "Example Node",
    "Image Selector": "Image Selector",
}
  1. Restart ComfyUI. Python changes only load at startup.
  2. Double-click the canvas and search for “Image Selector”, or find it under the example category.
  3. Test it: load several images into a batch (for example two Load Image nodes joined with a Batch Images node), connect them to Image Selector, and send the output to a Preview Image node.

The dictionary key ("Image Selector") must be unique across every installed node pack, so give real projects a prefix such as "MyPack_ImageSelector".

Add a Dropdown Option

A list of strings in INPUT_TYPES becomes a dropdown widget. Let users pick the brightest, reddest, greenest or bluest image:

@classmethod
def INPUT_TYPES(s):
    return {"required": {
        "images": ("IMAGE",),
        "mode": (["brightest", "reddest", "greenest", "bluest"],),
    }}

def choose_image(self, images, mode):
    batch_size = images.shape[0]
    brightness = list(torch.mean(image.flatten()).item() for image in images)
    if mode == "brightest":
        scores = brightness
    else:
        channel = 0 if mode == "reddest" else (1 if mode == "greenest" else 2)
        absolute = list(torch.mean(image[:, :, channel].flatten()).item() for image in images)
        scores = list(absolute[i] / (brightness[i] + 1e-8) for i in range(batch_size))
    best = scores.index(max(scores))
    result = images[best].unsqueeze(0)
    return (result,)

The method now receives mode as a named argument, matching the key in INPUT_TYPES. Number inputs work the same way, for example ("INT", {"default": 0, "min": 0, "max": 4096, "step": 64}).

Send Messages to the Browser

To show feedback in the UI, the server sends a message and a small JavaScript extension listens for it.

  1. Send from Python. Import the server and add a line before the return:
    from server import PromptServer
    
    # at the end of choose_image
    PromptServer.instance.send_sync(
        "example.imageselector.textmessage",
        {"message": f"Picked image {best+1}"})
    return (result,)

    The message type string should be unique to your node.

  2. Export a web directory in __init__.py:
    WEB_DIRECTORY = "./web/js"
    __all__ = ["NODE_CLASS_MAPPINGS", "WEB_DIRECTORY"]
  3. Create web/js/imageSelector.js:
    import { app } from "../../scripts/app.js";
    
    app.registerExtension({
      name: "example.imageselector",
      async setup() {
        function messageHandler(event) { alert(event.detail.message); }
        app.api.addEventListener("example.imageselector.textmessage", messageHandler);
      },
    });
  4. Restart ComfyUI, reload the browser tab and run the workflow. A pop-up names the picked image.

An alert is fine for a test, but swap it for a toast or a widget update in a real node, since pop-ups interrupt batch runs.

Convert to the V3 Schema

ComfyUI now has a V3 node schema on a versioned API. The docs say future node features will only be added to V3, so use it for new projects. The main changes:

  • Inputs and outputs are objects, not dictionaries.
  • The run method is always a class method named execute.
  • A comfy_entrypoint() function returning a ComfyExtension replaces NODE_CLASS_MAPPINGS.
  • Nodes hold no instance state; __init__ has no effect.

Here is the Image Selector in V3:

import torch
from comfy_api.latest import ComfyExtension, io

class ImageSelector(io.ComfyNode):
    @classmethod
    def define_schema(cls) -> io.Schema:
        return io.Schema(
            node_id="MyPack_ImageSelector",
            display_name="Image Selector",
            category="example",
            inputs=[
                io.Image.Input("images"),
                io.Combo.Input("mode", options=["brightest", "reddest", "greenest", "bluest"]),
            ],
            outputs=[io.Image.Output()],
        )

    @classmethod
    def execute(cls, images, mode) -> io.NodeOutput:
        brightness = [torch.mean(img.flatten()).item() for img in images]
        best = brightness.index(max(brightness))  # add the colour logic as above
        return io.NodeOutput(images[best].unsqueeze(0))

class MyExtension(ComfyExtension):
    async def get_node_list(self) -> list[type[io.ComfyNode]]:
        return [ImageSelector]

async def comfy_entrypoint() -> ComfyExtension:
    return MyExtension()

Import from comfy_api.latest to track the newest API, or pin a numbered version such as comfy_api.v0_0_2 for stability. Property names map across like this:

V1 V3
RETURN_TYPES outputs in the Schema
RETURN_NAMES display_name on each Output
FUNCTION Always execute
CATEGORY category
OUTPUT_NODE is_output_node
VALIDATE_INPUTS validate_inputs

Dropdowns in V3 use io.Combo.Input("mode", options=[...]). All core input and output classes are defined in comfy_api/latest/_io.py; check it when you upgrade ComfyUI, because the latest API version can still change.

Common Data Types

Type What it holds
IMAGE Tensor [B,H,W,C], values 0 to 1
MASK Tensor [B,H,W] (see our masks guide)
LATENT Dictionary with a samples tensor
MODEL, CLIP, VAE Loaded model objects
CONDITIONING Encoded prompts
INT, FLOAT, STRING, BOOLEAN Widget values

Publish to the Comfy Registry

The Comfy Registry powers ComfyUI-Manager, so publishing there makes your node installable in one click.

  1. Create a publisher at registry.comfy.org. The publisher id is permanent and appears in your node’s URL.
  2. Create a publishing API key for that publisher and store it safely.
  3. Generate metadata: run comfy node init to create pyproject.toml, then fill in name, version, PublisherId, DisplayName and Icon. The name cannot change later, and versions must follow semantic versioning.
  4. Exclude dev files such as tests or design assets with a .comfyignore file (same syntax as .gitignore).
  5. Publish: run comfy node publish and paste the key when asked. On Windows, paste with a right-click, because Ctrl+V can add a hidden character.

To publish automatically, save the key as a GitHub secret named REGISTRY_ACCESS_TOKEN and add the Comfy-Org/publish-node-action workflow. It publishes each time you bump the version in pyproject.toml.

Users can then install your pack with ComfyUI-Manager or by hand, as in our manual custom node install guide.

Troubleshooting

The node does not appear in the menu

Restart ComfyUI fully. Check that the class is in NODE_CLASS_MAPPINGS (V1) or returned by get_node_list (V3), and that __init__.py exports it.

“IMPORT FAILED” in the console

Your module raised an error on import, usually a typo or a missing package. Read the traceback above the message. Our import failed fix guide covers the common causes.

Output is the wrong shape or the next node crashes

Make sure images stay [B,H,W,C]. Use unsqueeze(0) on a single image and return a tuple.

JavaScript does not load

Export WEB_DIRECTORY in __all__, check the path, then hard-refresh the browser (Ctrl+Shift+R) after restarting.

Two packs clash

Your node key matches another pack. Use a unique prefix for every node id.

More errors are in our ComfyUI errors and fixes list.

FAQ

Do I need to know JavaScript to make a ComfyUI node?

No. Most nodes are pure Python. JavaScript is only needed for custom UI.

Should I use V1 or V3?

Use V3 for new nodes, since new features only land there. V1 nodes still load, so existing packs keep working.

Why do I have to restart ComfyUI?

Nodes are imported once at startup. Python changes need a restart; JavaScript changes need a browser reload.

Where do custom nodes go?

In ComfyUI/custom_nodes/, one folder per pack.

How do I add pip dependencies?

List them in requirements.txt; comfy node init copies them into pyproject.toml for the Registry.

Can Claude Code help write nodes?

Yes. The docs point to the community ComfyUI Custom Node Skills, which teach Claude the V1 and V3 node APIs.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a sunny cafe holding a tablet with a CUSTOM NODE card, hook build your own node