Skip to main content
Version: Next

Creating TODOs from Software Templates

Scaffolder​

What is Backstage Scaffolder?​

Backstage Scaffolder lets users create or update software by filling in a form in Backstage. The form and the steps that run afterward are defined in a Software Template.

Each step calls an action, which is a backend function that performs one task. For example, an action can create a repository, write a file, or call another Backstage plugin. The custom action guide explains how a backend module adds actions to Scaffolder.

What to expect​

In this guide, you will add a todo:create action. A Software Template will use the action to add onboarding TODOs to an existing Component:

User runs a Software Template
-> template calls todo:create
-> todo:create asks the todo backend to create all the TODOs in one request
-> TODOs appear in the Component tab, Search, and Notifications

The action calls the todo backend instead of writing to the TODO database directly. This means the ownership check from the Permissions chapter still decides whether the user may create the TODOs. The action sends every TODO in a single batch request, and the backend saves them together or not at all. A failed template run therefore never leaves some TODOs created, and retrying it does not duplicate them.

Prerequisites​

Before starting:

  • Complete Notifications. The owner-based creation check from the Permissions chapter must be working.
  • Choose an existing Component with exactly one owning Group. Sign in as a member of that Group when you test the template.

Creating the Scaffolder action​

Step 1: Create a backend module​

Create a module for the Scaffolder plugin:

yarn new --select backend-plugin-module --option pluginId=scaffolder

Name the module todo when prompted, then add its dependencies:

yarn workspace @internal/backstage-plugin-scaffolder-backend-module-todo add @backstage/errors @backstage/plugin-scaffolder-node

Step 2: Add a batch endpoint to the todo backend​

Creating TODOs one request at a time is not atomic. If a later request failed, the earlier TODOs would already be saved, and running the template again would create them twice. Instead, add a POST /todos/batch route that checks ownership once, limits the batch size, and saves every TODO in a single database insert.

Add the batch method to the service. It looks up the Component once and inserts all rows in one statement, so either every TODO is saved or none is:

plugins/todo-backend/src/services/TodoListService.ts
async createTodoBatch(
input: {
entityRef: string;
items: { title: string; dueAt?: string }[];
},
options: {
credentials: BackstageCredentials<BackstageUserPrincipal>;
},
): Promise<TodoItem[]> {
const entity = await this.#catalog.getEntityByRef(input.entityRef, {
credentials: options.credentials,
});
if (!entity) {
throw new NotFoundError('Entity not found');
}

const forEntityRef = stringifyEntityRef(entity);
const entityDisplay = entity.metadata.title ?? input.entityRef;
const createdBy = options.credentials.principal.userEntityRef;
const createdAt = new Date().toISOString();

const todos: TodoItem[] = input.items.map(item => ({
id: crypto.randomUUID(),
title: `[${entityDisplay}] ${item.title}`,
createdBy,
forEntityRef,
dueAt: item.dueAt,
createdAt,
}));

await this.#database('todo').insert(
todos.map(todo => this.toDatabaseRow(todo)),
);
return todos;
}

Import NotFoundError from @backstage/errors in the service. Then add the route. Move the Component lookup and ownership check from POST /todos into a shared helper so that both routes enforce the same rule:

plugins/todo-backend/src/router.ts
const MAX_BATCH_SIZE = 20;

const todoBatchSchema = z.object({
entityRef: z.string(),
items: z
.array(
z.object({
title: z.string(),
dueAt: z.string().datetime().optional(),
}),
)
.min(1)
.max(MAX_BATCH_SIZE),
});

async function assertOwnsEntity(
entityRef: string,
credentials: BackstageCredentials<BackstageUserPrincipal>,
) {
const entity = await catalog.getEntityByRef(entityRef, { credentials });
if (!entity) {
throw new NotFoundError('Entity not found');
}

const { ownershipEntityRefs } = await userInfo.getUserInfo(credentials);
const ownsEntity = (entity.relations ?? []).some(
relation =>
relation.type === RELATION_OWNED_BY &&
ownershipEntityRefs.includes(relation.targetRef),
);
if (!ownsEntity) {
throw new NotAllowedError(
'Only the owning Group may create TODOs for this entity',
);
}
}

router.post('/todos/batch', async (req, res) => {
const parsed = todoBatchSchema.safeParse(req.body);
if (!parsed.success) {
throw new InputError(parsed.error.toString());
}

const credentials = await httpAuth.credentials(req, { allow: ['user'] });
await assertOwnsEntity(parsed.data.entityRef, credentials);

const items = await todoList.createTodoBatch(parsed.data, { credentials });
res.status(201).json({ items });
});

Call assertOwnsEntity from POST /todos as well, in place of the inline check from the Permissions chapter. Register /todos/batch before the parameterized /todos/:id route, as you did for /todos/index in the Search chapter.

Step 3: Implement todo:create​

The action receives a Component reference and a list of TODO titles. When a user runs the template, the action passes that user's identity to the todo backend. The todo backend can then apply the same ownership check used by the frontend.

The action's schema describes the values the template must provide and the values the action returns. Scaffolder shows this information on the Installed actions page.

plugins/scaffolder-backend-module-todo/src/actions/createTodoAction.ts
import type {
AuthService,
DiscoveryService,
} from '@backstage/backend-plugin-api';
import { InputError } from '@backstage/errors';
import { createTemplateAction } from '@backstage/plugin-scaffolder-node';

export function createTodoAction(options: {
auth: AuthService;
discovery: DiscoveryService;
}) {
return createTemplateAction({
id: 'todo:create',
description: 'Creates TODOs for a Catalog Component',
schema: {
input: z =>
z.object({
entityRef: z
.string()
.describe('Catalog entity ref that the TODOs concern'),
items: z
.array(
z.object({
title: z.string(),
dueAt: z.string().datetime().optional(),
}),
)
.min(1)
.max(20),
}),
output: z =>
z.object({
ids: z.array(z.string()),
}),
},
async handler(ctx) {
const baseUrl = await options.discovery.getBaseUrl('todo');
const { token } = await options.auth.getPluginRequestToken({
onBehalfOf: await ctx.getInitiatorCredentials(),
targetPluginId: 'todo',
});

const response = await fetch(`${baseUrl}/todos/batch`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
entityRef: ctx.input.entityRef,
items: ctx.input.items,
}),
signal: ctx.signal,
});

if (!response.ok) {
throw new InputError(
`Failed to create TODOs: ${response.status} ${response.statusText}`,
);
}

const { items } = await response.json();
const ids: string[] = items.map((todo: { id: string }) => todo.id);

ctx.output('ids', ids);
},
});
}

The POST /todos/batch route must perform the ownership check from the Permissions chapter. The action sends a request as the user who started the template, not as an unrestricted backend service. Do not let the Component selected in the template bypass that check.

Step 4: Register the action​

plugins/scaffolder-backend-module-todo/src/module.ts
import {
coreServices,
createBackendModule,
} from '@backstage/backend-plugin-api';
import { scaffolderActionsExtensionPoint } from '@backstage/plugin-scaffolder-node';
import { createTodoAction } from './actions/createTodoAction';

export const scaffolderModuleTodo = createBackendModule({
pluginId: 'scaffolder',
moduleId: 'todo',
register(env) {
env.registerInit({
deps: {
actions: scaffolderActionsExtensionPoint,
auth: coreServices.auth,
discovery: coreServices.discovery,
},
async init({ actions, auth, discovery }) {
actions.addActions(createTodoAction({ auth, discovery }));
},
});
},
});

yarn new already added the module to packages/backend/src/index.ts. Confirm that this line is present, and add it only if it is missing. Registering the same module twice prevents the backend from starting:

backend.add(
import('@internal/backstage-plugin-scaffolder-backend-module-todo'),
);

Restart the backend, then open http://localhost:3000/create/actions. Search the Installed actions page for todo:create and confirm that it shows the expected input and output.

Step 5: Create an onboarding template​

Use an entity picker to let the user choose an existing Component:

templates/todo-onboarding/template.yaml
apiVersion: scaffolder.backstage.io/v1beta3
kind: Template
metadata:
name: todo-onboarding
title: Add component onboarding TODOs
spec:
owner: group:default/backstage-admins
type: service
parameters:
- title: Select a component
required:
- entityRef
properties:
entityRef:
title: Component
type: string
ui:field: EntityPicker
ui:options:
catalogFilter:
kind: Component
steps:
- id: createTodos
name: Create onboarding TODOs
action: todo:create
input:
entityRef: ${{ parameters.entityRef }}
items:
- title: Review the component documentation
- title: Configure production monitoring
output:
text:
- title: Created TODOs
content: ${{ steps.createTodos.output.ids | join(', ') }}

Register the template by adding its file to the Catalog locations in app-config.yaml. Paths for local files are resolved from the backend package, so this path points from packages/backend to the repository-level templates directory:

app-config.yaml
catalog:
locations:
- type: file
target: ../../templates/todo-onboarding/template.yaml
rules:
- allow: [Template]

If catalog.locations already exists, add only the new list item rather than a second catalog block. Also replace group:default/backstage-admins in the template's spec.owner with a Group that exists in your Catalog.

Step 6: Verify the workflow​

  1. Sign in as a member of a component's owning Group.
  2. Open Create, run Add component onboarding TODOs, and select that component.
  3. Confirm the template task reports the created TODO ids.
  4. Open the component's Todos tab and confirm both items appear.
  5. Search for one of the titles and confirm the result opens that tab.
  6. Run the template as a non-owner and confirm the todo backend rejects the create request.

If the action succeeds for a non-owner, first check that it sends the identity of the user who started the template. Then check that POST /todos/batch applies the Component ownership rule from the Permissions chapter.

What you did​

You registered a todo:create Scaffolder action and used it from a Software Template that creates onboarding TODOs for a selected Component. The action passes along the identity of the user who started the template, so the todo backend can apply its normal creation check.

Members of the owning Group can run the template, while a non-owner cannot use the action to bypass the todo plugin's permissions.

Next step​

Continue to Actions and MCP to expose the same owner-authorized TODO workflow as MCP tools.