Stacks Actions
Server actions are reusable business logic units invoked from routes, events, or CLI commands.
Key Paths
- Core package:
storage/framework/core/actions/src/
- Application actions:
app/Actions/
- Default framework actions:
storage/framework/defaults/app/Actions/
- Framework actions (generated):
storage/framework/actions/
Creating an Action
// app/Actions/CreateWidget.ts
import { Action } from '@stacksjs/actions'
import { toSnakeCaseKeys } from '@stacksjs/orm'
import { response } from '@stacksjs/router'
export default new Action({
name: 'Create Widget',
description: 'Create a widget',
method: 'POST',
model: Widget,
async handle(request: RequestInstance) {
await request.validate()
const widget = await Widget.create(toSnakeCaseKeys(request.all()))
return response.json(widget, 201)
},
})
Use the Action class, an explicit HTTP method, and response helpers. Store and
update actions should set model and call request.validate() before persisting
input. Import framework helpers explicitly, following the default actions.
Resource Action Contract
Show, update, and destroy actions must distinguish malformed identifiers,
missing records, invalid input, and operational failures:
- Read resource identifiers from
request.getParam('id'), never from the
request body.
- Convert the value to a number and require a safe positive integer. Return
422 when it is malformed.
- Validate update input with the action model, then normalize persisted keys
with
toSnakeCaseKeys(request.all()) when the service expects database
column names.
- Core update services return
undefined when the row does not exist. Core
destroy services return false. They throw only for invalid domain input,
conflicts, or real operational failures.
- Return
404 when show or update returns undefined, or destroy returns
false. Never return a successful null, an unconditional 204, or a
generic 500 for an absent row.
- Preserve domain status codes such as
409 for uniqueness conflicts and
422 for relationship or state validation.
Share identifier and not-found response helpers inside a domain instead of
copying the contract across every resource. The built-in Commerce actions use
Actions/Commerce/commerce-action.ts as the reference implementation.
Auto-Generated API Actions (useApi Trait)
When a model defines useApi, the framework auto-generates REST actions:
defineModel({
name: 'Product',
traits: {
useApi: {
uri: 'products',
routes: ['index', 'store', 'show', 'update', 'destroy']
}
}
})
This generates:
GET /api/products → Index action (list all)
POST /api/products → Store action (create)
GET /api/products/{id} → Show action (get one)
PUT /api/products/{id} → Update action
DELETE /api/products/{id} → Destroy action
Default Framework Actions (80+)
Authentication Actions
LoginAction — POST /login (validates email + password, returns token + user)
RegisterAction — POST /register
LogoutAction — POST /logout (auth required)
RefreshTokenAction — POST /auth/refresh
CreateTokenAction — POST /auth/token
ListTokensAction — GET /auth/tokens (auth required)
RevokeTokenAction — DELETE /auth/tokens/{id}
GetMeAction — GET /me (auth required)
PasskeyRegistrationAction — passkey authentication options
Dashboard Settings Actions (40+)
For each settings category (AI, Analytics, App, Cache, Cloud, Database, DNS, Email, Environment, FileSystems, Hashing, Library, Logging, Notifications, Payment, Ports, Queue, SearchEngine, Security, Services, Storage, Team, UI):
Get{Category}SettingsAction — read current settings
Update{Category}SettingsAction — update settings
Commerce Actions
- CRUD actions for: Products, Orders, Customers, Payments, Coupons, GiftCards, Reviews, Shipping, DeliveryRoutes, TaxRates, LicenseKeys, etc.
Content Actions
- CRUD actions for: Posts, Pages, Authors, Categories, Tags, Comments
System Actions
HealthAction — GET /health (returns status, uptime, memory, PID, Bun version)
GetUserCountAction — user count for dashboard
GetSubscriberCountAction — subscriber count
- Deployment CRUD actions
- Job monitoring actions
- Notification actions
- Request analytics actions
Action Handler Pattern
Actions receive the enhanced request object:
async handle(request: EnhancedRequest) {
const name = request.get('name') // input value
const email = request.input('email') // alias
const all = request.all() // all input
const user = await request.user() // authenticated user
return { success: true, data: { ... } }
}
Using Actions in Routes
// String-based (auto-loaded)
route.post('/users', 'Actions/CreateUser')
// In events (app/Events.ts)
{ 'user:registered': ['SendWelcomeEmail'] } // action name as listener
CLI Commands
buddy make:action [name] — scaffold a new action
Gotchas
- Application actions go in
app/Actions/
- Framework default actions are in
storage/framework/defaults/app/Actions/
- The
handle() method is required — it receives the request object
- Actions used as event listeners also have a
handle(event) method
- The
useApi model trait auto-generates CRUD actions + routes
- Actions are resolved dynamically at runtime via string names
- The HealthAction at
/health is useful for container health checks
- Login action returns
{ token: string, user: { id, email, name } }
- All dashboard settings actions read/write from the corresponding config files
1---2name: stacks-actions-43description: Use when working with Stacks server actions — creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 80+ default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/app/Actions/.4license: MIT5compatibility: Bun >= 1.3.0, TypeScript6allowed-tools: Read Edit Write Bash Grep Glob7metadata:8 source: https://skillmd.com/skills/stacksjs/stacks-actions-49---1011# Stacks Actions1213Server actions are reusable business logic units invoked from routes, events, or CLI commands.1415## Key Paths16- Core package: `storage/framework/core/actions/src/`17- Application actions: `app/Actions/`18- Default framework actions: `storage/framework/defaults/app/Actions/`19- Framework actions (generated): `storage/framework/actions/`2021## Creating an Action2223```typescript24// app/Actions/CreateWidget.ts25import { Action } from '@stacksjs/actions'26import { toSnakeCaseKeys } from '@stacksjs/orm'27import { response } from '@stacksjs/router'2829export default new Action({30 name: 'Create Widget',31 description: 'Create a widget',32 method: 'POST',33 model: Widget,3435 async handle(request: RequestInstance) {36 await request.validate()3738 const widget = await Widget.create(toSnakeCaseKeys(request.all()))3940 return response.json(widget, 201)41 },42})43```4445Use the `Action` class, an explicit HTTP method, and `response` helpers. Store and46update actions should set `model` and call `request.validate()` before persisting47input. Import framework helpers explicitly, following the default actions.4849## Resource Action Contract5051Show, update, and destroy actions must distinguish malformed identifiers,52missing records, invalid input, and operational failures:53541. Read resource identifiers from `request.getParam('id')`, never from the55 request body.562. Convert the value to a number and require a safe positive integer. Return57 `422` when it is malformed.583. Validate update input with the action model, then normalize persisted keys59 with `toSnakeCaseKeys(request.all())` when the service expects database60 column names.614. Core update services return `undefined` when the row does not exist. Core62 destroy services return `false`. They throw only for invalid domain input,63 conflicts, or real operational failures.645. Return `404` when show or update returns `undefined`, or destroy returns65 `false`. Never return a successful `null`, an unconditional `204`, or a66 generic `500` for an absent row.676. Preserve domain status codes such as `409` for uniqueness conflicts and68 `422` for relationship or state validation.6970Share identifier and not-found response helpers inside a domain instead of71copying the contract across every resource. The built-in Commerce actions use72`Actions/Commerce/commerce-action.ts` as the reference implementation.7374## Auto-Generated API Actions (useApi Trait)7576When a model defines `useApi`, the framework auto-generates REST actions:7778```typescript79defineModel({80 name: 'Product',81 traits: {82 useApi: {83 uri: 'products',84 routes: ['index', 'store', 'show', 'update', 'destroy']85 }86 }87})88```8990This generates:91- `GET /api/products` → Index action (list all)92- `POST /api/products` → Store action (create)93- `GET /api/products/{id}` → Show action (get one)94- `PUT /api/products/{id}` → Update action95- `DELETE /api/products/{id}` → Destroy action9697## Default Framework Actions (80+)9899### Authentication Actions100- `LoginAction` — POST /login (validates email + password, returns token + user)101- `RegisterAction` — POST /register102- `LogoutAction` — POST /logout (auth required)103- `RefreshTokenAction` — POST /auth/refresh104- `CreateTokenAction` — POST /auth/token105- `ListTokensAction` — GET /auth/tokens (auth required)106- `RevokeTokenAction` — DELETE /auth/tokens/{id}107- `GetMeAction` — GET /me (auth required)108- `PasskeyRegistrationAction` — passkey authentication options109110### Dashboard Settings Actions (40+)111For each settings category (AI, Analytics, App, Cache, Cloud, Database, DNS, Email, Environment, FileSystems, Hashing, Library, Logging, Notifications, Payment, Ports, Queue, SearchEngine, Security, Services, Storage, Team, UI):112- `Get{Category}SettingsAction` — read current settings113- `Update{Category}SettingsAction` — update settings114115### Commerce Actions116- CRUD actions for: Products, Orders, Customers, Payments, Coupons, GiftCards, Reviews, Shipping, DeliveryRoutes, TaxRates, LicenseKeys, etc.117118### Content Actions119- CRUD actions for: Posts, Pages, Authors, Categories, Tags, Comments120121### System Actions122- `HealthAction` — GET /health (returns status, uptime, memory, PID, Bun version)123- `GetUserCountAction` — user count for dashboard124- `GetSubscriberCountAction` — subscriber count125- Deployment CRUD actions126- Job monitoring actions127- Notification actions128- Request analytics actions129130## Action Handler Pattern131132Actions receive the enhanced request object:133```typescript134async handle(request: EnhancedRequest) {135 const name = request.get('name') // input value136 const email = request.input('email') // alias137 const all = request.all() // all input138 const user = await request.user() // authenticated user139140 return { success: true, data: { ... } }141}142```143144## Using Actions in Routes145146```typescript147// String-based (auto-loaded)148route.post('/users', 'Actions/CreateUser')149150// In events (app/Events.ts)151{ 'user:registered': ['SendWelcomeEmail'] } // action name as listener152```153154## CLI Commands155- `buddy make:action [name]` — scaffold a new action156157## Gotchas158- Application actions go in `app/Actions/`159- Framework default actions are in `storage/framework/defaults/app/Actions/`160- The `handle()` method is required — it receives the request object161- Actions used as event listeners also have a `handle(event)` method162- The `useApi` model trait auto-generates CRUD actions + routes163- Actions are resolved dynamically at runtime via string names164- The HealthAction at `/health` is useful for container health checks165- Login action returns `{ token: string, user: { id, email, name } }`166- All dashboard settings actions read/write from the corresponding config files