Skip to content
GitHub

Strutvane 0.2 is still being built. These pages describe how it will work; anything marked "Coming in 0.2" doesn't exist yet. Release notes and support policy.

Routing

View as Markdownllms.txt

A route connects a URL and an HTTP method (GET, POST…) to the code that answers it. Your routes live in two files:

  • routes/api.ts: your JSON API. Every route here is served under /api and gets the api middleware group (CSRF check and rate limit).
  • routes/web.ts: pages for the browser (the React app’s HTML shell). These get the web group (CSRF check).
routes/api.ts
import { defineRoutes, Route } from '@strutvane/framework'
export default defineRoutes([
Route.get('/hello', (ctx) => ctx.json({ message: 'Hello!' })).name('hello'),
])

Start the app (npm run dev, or node strut serve) and call it:

Terminal window
curl http://localhost:3000/api/hello

What you’ll see:

{ "message": "Hello!" }

The route was defined as /hello, but it’s served at /api/hello, because everything in routes/api.ts gets the /api prefix.

Route.get() doesn’t register anything. It returns a route object, and defineRoutes([...]) returns the list. bootstrap/app.ts hands the lists to the app:

bootstrap/app.ts
.withRouting({ web, api, health: '/up', bindings: { post: Post } })

Why values? Your routes file can be imported twice (by the server, node strut route:list and your tests) without registering anything twice, and TypeScript can read every name and path from typeof api.

The decided shape for 0.2 is Laravel’s: a routes file exports a callback that receives the router, and bootstrap/app.ts passes the files to withRouting():

routes/api.ts
import type { Router } from '@strutvane/framework'
import { PostController } from '../app/http/controllers/post.controller.ts'
export default (router: Router) => {
router.get('/hello', (ctx) => ctx.json({ message: 'Hello!' })).name('hello')
router.apiResource('posts', PostController, { bindBy: 'slug' })
}
bootstrap/app.ts
export default Application.configure({ basePath: dirname(import.meta.dirname) })
.withRouting({ web, api })
.withMiddleware((middleware) => { /* … */ })
.withExceptions((exceptions) => { /* … */ })
.create()

The callback is still only called by Strutvane when it builds the route table, so importing the file registers nothing, and route names stay typed.

There’s one method per HTTP verb, plus match for several at once:

routes/api.ts
import { defineRoutes, Route } from '@strutvane/framework'
import { ReportController } from '../app/http/controllers/report.controller.ts'
export default defineRoutes([
Route.get('/reports', [ReportController, 'index']),
Route.post('/reports', [ReportController, 'store']),
Route.put('/reports/{report}', [ReportController, 'replace']),
Route.patch('/reports/{report}', [ReportController, 'update']),
Route.delete('/reports/{report}', [ReportController, 'destroy']),
Route.match(['GET', 'POST'], '/reports/search', [ReportController, 'search']),
])

The second argument is the action: either [ControllerClass, 'methodName'], or a function (ctx) => Response for tiny routes. A method name that doesn’t exist on the controller is a compile error.

Give a route a name with .name(), then build its URL anywhere with route():

routes/api.ts
Route.post('/posts/{post:slug}/publish', [PostController, 'publish']).name('posts.publish'),
app/http/controllers/post.controller.ts
return ctx.json({ links: { publish: route('posts.publish', { post }) } })

What you’ll see in the response:

{ "links": { "publish": "/api/posts/hello-world/publish" } }
Call Result
route('posts.index') /api/posts
route('posts.show', { post }) /api/posts/hello-world (a model fills the parameter with the field the route binds by)
route('posts.show', { post: 'hello-world' }) /api/posts/hello-world (a plain string or number works too)
route('posts.index', {}, { query: { page: 2, sort: '-created_at' } }) /api/posts?page=2&sort=-created_at
route('posts.show', { post }, { absolute: true }) http://localhost:3000/api/posts/hello-world (prefixed with APP_URL)

These are compile errors, caught before you run anything:

route('posts.shwo', { post }) // no route has that name
route('posts.show') // {post} is required
route('posts.show', { pots: post }) // wrong parameter name

To make this work, bootstrap/app.ts has one block that tells TypeScript about your routes (new apps already have it):

bootstrap/app.ts
declare module '@strutvane/framework' {
interface RouteRegistry extends RoutesOf<[typeof web, typeof api]> {}
}

A part of the path in braces is a parameter: {report} matches any value in that position. Read it as a string with ctx.param():

Route.get('/reports/{report}', (ctx) => ctx.json({ id: ctx.param('report') })),

GET /api/reports/42 answers { "id": "42" }.

Parameter names use letters, digits and underscores, and each name appears once per path.

Usually a parameter stands for a database record. Route model binding looks the record up for you before your controller runs. Register which model a parameter name means, once, in bootstrap/app.ts:

bootstrap/app.ts
.withRouting({ web, api, health: '/up', bindings: { post: Post, author: Author } })

Now any route with {post} gets a Post:

routes/api.ts
Route.get('/posts/{post}', [PostController, 'show']),
app/http/controllers/post.controller.ts
show(ctx: HttpContext): Response {
const post = ctx.model(Post) // typed as Post
return ctx.json({ data: post })
}

What you’ll see:

Request Response
GET /api/posts/1 (exists) 200 with the post
GET /api/posts/999 (missing) 404: No post matches "999".

Add :field to look the record up by another column. {post:slug} finds the post whose slug matches:

Route.get('/posts/{post:slug}', [PostController, 'show']),

GET /api/posts/hello-world → the post with slug hello-world. And route('posts.show', { post }) builds /api/posts/hello-world from the model.

Binding runs after middleware, so a guest on an auth route gets 401 before they can learn whether a record exists.

A group shares a path prefix, a name prefix and middleware between routes:

routes/api.ts
import { defineRoutes, Route } from '@strutvane/framework'
import { StatsController } from '../app/http/controllers/stats.controller.ts'
import { UserAdminController } from '../app/http/controllers/user-admin.controller.ts'
export default defineRoutes([
Route.group({ prefix: 'admin', name: 'admin.', middleware: ['auth', 'admin'] }, [
Route.get('/stats', [StatsController, 'show']).name('stats'),
Route.get('/users', [UserAdminController, 'index']).name('users'),
]),
])

What you’ll see in node strut route:list:

Method URI Name Action Middleware
------ ---------------- ----------- ------------------------- ----------------
GET /api/admin/stats admin.stats StatsController@show api, auth, admin
GET /api/admin/users admin.users UserAdminController@index api, auth, admin

The name prefix is typed too: route('admin.stats') compiles, route('stats') doesn’t. Groups can be nested; prefixes, names and middleware add up.

Fluent groups: Route.middleware(...).group(...)

Section titled “Fluent groups: Route.middleware(...).group(...)”

When all you share is middleware, the fluent form reads like Laravel’s Route::middleware([...])->group(...). The middleware names are separate arguments, and .group() takes the routes either from a callback (Laravel’s shape) or as an array:

routes/api.ts
import { defineRoutes, Route } from '@strutvane/framework'
import { ProfileController } from '../app/http/controllers/profile.controller.ts'
import { StatsController } from '../app/http/controllers/stats.controller.ts'
export default defineRoutes([
// the callback form, as in Laravel: register the routes inside the callback
Route.middleware('auth').group(() => {
Route.get('/me', [ProfileController, 'show']).name('me')
Route.patch('/me', [ProfileController, 'update']).name('me.update')
}),
// also accepted: return an array from the callback, or pass the array directly
Route.middleware('auth', 'can:view-stats').group([
Route.get('/admin/stats', [StatsController, 'show']).name('admin.stats'),
]),
])

Inside the callback, Route.get() and friends add their routes to that group, exactly like Laravel. The callback runs only when Strutvane builds the route table, never when the file is imported, so loading a routes file twice (the server, route:list, your tests) still registers nothing twice.

Everything in routes/api.ts is under /api. Versioning is opt-in: put the routes of each version in a group with a prefix and a name prefix:

routes/api.ts
Route.group({ prefix: 'v1', name: 'v1.' }, [
Route.apiResource('posts', PostController), // /api/v1/posts, named v1.posts.index …
]),

A shorter Route.prefix('v1').group(…) form is planned for 0.2.

Add middleware to one route with .middleware():

Route.get('/me', (ctx) => ctx.json({ data: ctx.requireUser() })).name('me').middleware('auth'),

Middleware can take parameters after a colon: 'auth:optional', 'throttle:5,1'. See Middleware.

A route can drop middleware its group added. The classic case is a webhook from another service, which can’t carry your CSRF token:

routes/api.ts
Route.post('/webhooks/stripe', [StripeWebhookController, 'handle']).withoutMiddleware('csrf'),

The same works for whole groups (Route.withoutMiddleware('csrf').group([...]), or Route.group({ withoutMiddleware: ['csrf'] }, [...])) and resources (.withoutMiddleware('throttle')). Every opt-out is listed by node strut route:list --security, so a reviewer sees it. A webhook still needs its own check, usually a signature from the sender. See CSRF Protection.

To exempt paths app-wide instead, list them in bootstrap/app.ts: .withMiddleware((m) => m.validateCsrfTokens({ except: ['api/webhooks/*'] })). Patterns match the full path without the leading slash, api/ prefix included, so webhooks/* alone would never match an API route (a start-up warning for patterns that can never match is coming in 0.2).

Route.post('/login', [LoginController, 'store']).middleware('throttle:5,1'), // 5 per minute
Route.get('/search', [SearchController, 'index']).middleware('throttle:search'), // a named limiter

Every /api route already has throttle:api (60 requests per minute per user, or per IP for guests). See Rate Limiting.

A signed URL has a signature on the end, made with your APP_KEY. Anyone can open it, but nobody can change it. Use it for links you email: unsubscribe, download, confirm.

  1. Protect the route with signed:

    routes/api.ts
    Route.get('/downloads/{file}', [DownloadController, 'show']).name('downloads.show').middleware('signed'),
  2. Make the link with the typed helpers (same arguments as route()):

    import { url } from '@strutvane/framework'
    url.signedRoute('downloads.show', { file: 'report-2026.pdf' })
    url.signedRoute('downloads.show', { file: 'report-2026.pdf' }, { expiresIn: 3600, oneTime: true }) // 1 hour, usable once
    url.temporarySignedRoute('downloads.show', new Date(Date.now() + 30 * 60_000), { file: 'report-2026.pdf' }) // 30 minutes

What you’ll see:

Request Answer
The link as made 200, your controller runs
The link with anything changed 403 invalid_signature: “This link is not valid. It may have been changed or copied incompletely.”
A temporary link after it expired 403 signature_expired: “This link has expired. Ask for a new one.”

signed runs before auth, so a bad link is refused whoever you are.

Most models need the same set of routes. One line gives you all of them, with standard names.

Route.resource(): seven routes (with form pages)

Section titled “Route.resource(): seven routes (with form pages)”
Route.resource('posts', PostController),
Method URI Name Action
GET /posts posts.index index
GET /posts/create posts.create create
POST /posts posts.store store
GET /posts/{post} posts.show show
GET /posts/{post}/edit posts.edit edit
PUT|PATCH /posts/{post} posts.update update
DELETE /posts/{post} posts.destroy destroy

The parameter name is the singular of the resource name: posts → {post}.

Route.apiResource(): five routes (no form pages)

Section titled “Route.apiResource(): five routes (no form pages)”

APIs don’t need create and edit pages, so apiResource leaves them out:

routes/api.ts
Route.apiResource('posts', PostController),

You get index, store, show, update and destroy. Pair it with a ResourceController and every action works with no further code. See Controllers.

Option What it does Example
only Keep just these actions { only: ['index', 'show'] }
except Drop these actions { except: ['destroy'] }
bindBy Bind the parameter by this column { bindBy: 'slug' } → /posts/{post:slug}
parameter Rename the parameter (for irregular plurals) Route.resource('news', NewsController, { parameter: 'story' }) → {story}

And two methods to add middleware to the whole resource or to some actions:

routes/api.ts
Route.apiResource('posts', PostController, { bindBy: 'slug' })
.middlewareFor(['index', 'show'], 'auth:optional')
.middlewareFor(['store', 'update', 'destroy'], 'auth'),
Route.apiResource('authors', AuthorController, { only: ['index', 'show', 'store'] })
.middleware('throttle:30,1'),

The controller must have a method for every action you keep; if it doesn’t, the line doesn’t compile.

Every app has /up: a route that answers 200 to GET and HEAD when the app is alive, for load balancers, uptime checks and the Docker HEALTHCHECK. It stays reachable in maintenance mode. (In the prototype it’s switched on with health: '/up' in withRouting.)

Terminal window
curl http://localhost:3000/up

What you’ll see:

{ "status": "ok" }

/up only says the process is alive. A readiness route, /ready (“the database and other services answer too”), comes in 0.3 with the health-check registry.

When the path exists but not for that method, you get 405 and an Allow header naming the methods that work:

Terminal window
curl -i -X DELETE http://localhost:3000/api/hello
HTTP/1.1 405 Method Not Allowed
allow: GET
{"type":"https://strutvane.dev/problems/method_not_allowed","title":"Method not allowed","status":405,"code":"method_not_allowed","detail":"DELETE is not supported here. Use GET."}

A path that doesn’t exist at all is a 404: Nothing is at GET /api/helo.

Action Example Use it for
A closure (ctx) => Response Route.get('/ping', (ctx) => ctx.json({ pong: true })) One-liners, health checks, prototypes
A controller method [Controller, 'method'] Route.get('/reports', [ReportController, 'index']) Everything else: testable, injectable, shows as ReportController@index in route:list
A resource Route.apiResource('posts', PostController) A model’s standard actions

A closure can also carry protections, with a wrapper: withAuth(async (ctx) => …). See Middleware.

Laravel’s Route::fallback(): one route that answers when nothing else matches, instead of the default 404 problem. Useful for a custom “not found” page.

routes/web.ts
Route.fallback([SpaController, 'show']), // let the React app show its own "not found" screen

It runs only after every other route failed to match, and still goes through the group’s middleware.

Laravel’s Route::domain('{account}.example.com'): routes that match a host name, with the subdomain as a parameter. It’s planned together with teams picked by subdomain (acme.yourapp.com, installer question 12). Until then, every route answers on every trusted host.

Some resources exist once per parent: a user’s profile, a team’s settings. There’s no id in the URL and no list:

Route.singleton('profile', ProfileController),
Method URI Name Action
GET /profile profile.show show
GET /profile/edit profile.edit edit
PUT|PATCH /profile profile.update update

Nested and shallow resources: { shallow: true }

Section titled “Nested and shallow resources: { shallow: true }”

A nested resource lives under its parent: the comments of a post. Shallow nesting keeps the parent only where it’s needed (listing and creating), so a single comment has a short URL:

Route.apiResource('posts.comments', CommentController, { shallow: true }),
Method URI Name
GET /posts/{post}/comments posts.comments.index
POST /posts/{post}/comments posts.comments.store
GET /comments/{comment} comments.show
PUT|PATCH /comments/{comment} comments.update
DELETE /comments/{comment} comments.destroy

HTML forms can only send GET and POST. To send PUT, PATCH or DELETE from a plain HTML form, add a hidden _method field to a POST:

<form method="post" action="/posts/hello-world">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="…">
<button>Delete</button>
</form>

Only POST can be turned into PUT, PATCH or DELETE (a GET never becomes a write), and the CSRF check still applies to the spoofed request. The React UI doesn’t need this: it sends real methods.

Laravel’s ->block(): while one request of a user’s session runs on this route, a second one waits, so two quick clicks on “Pay” can’t run side by side. Planned as .block() on a route. For API calls today, use the idempotent middleware: a retry with the same Idempotency-Key gets the first response instead of running twice. See Middleware.

Terminal window
node strut route:list # every route
node strut route:list --path posts # only URIs containing "posts"
node strut route:list --name admin. # only names containing "admin."
node strut route:list --security # the protections that really apply, opt-outs and warnings
node strut route:list --json # machine-readable

With Docker, type the same commands: node strut forwards them into the app container.

What you’ll see (the example app, shortened):

Method URI Name Action Middleware
--------- ------------------------------ ------------- --------------------- ----------------
GET /api/posts posts.index PostController@index api, auth:optional
POST /api/posts posts.store PostController@store api, auth
GET /api/posts/{post:slug} posts.show PostController@show api, auth:optional
PUT|PATCH /api/posts/{post:slug} posts.update PostController@update api, auth
DELETE /api/posts/{post:slug} posts.destroy PostController@destroy api, auth
POST /api/posts/{post:slug}/publish posts.publish PostController@publish api, auth
✖ No middleware is called "auht" (used by GET /api/me).
→ Did you mean "auth"?

Fix: correct the alias. Strutvane checks every alias when the app starts, so this shows up in route:list and your tests, never in production.

“… binds {post:slug}, but no model is bound to “post””

Section titled ““… binds {post:slug}, but no model is bound to “post”””
✖ /api/posts/{post:slug} binds {post:slug}, but no model is bound to "post".
→ Add it in bootstrap/app.ts: withRouting({ bindings: { post: YourModel } }).

Fix:

bootstrap/app.ts
.withRouting({ web, api, bindings: { post: Post } })
✖ Two routes are named "posts.show": /api/posts/{post:slug} and /api/articles/{post}.
→ Route names must be unique, because route() would not know which URL to build. Rename one of them.
✖ GET /api/posts is registered twice.
→ The second one could never run. Remove it, or change its path or method.
✖ The route path "/posts/{post" has an unmatched brace.
→ Write parameters as {post} or {post:slug}.

“route(‘…’) needs a value for {post}”

Section titled ““route(‘…’) needs a value for {post}””
✖ route('posts.show') needs a value for {post}.
→ Pass every parameter of /api/posts/{post:slug}: { post }.

This only happens when the name comes from a variable (otherwise it’s a compile error). Fix: pass the parameter: route('posts.show', { post }).

“… both adds “csrf” and opts out of it”

Section titled ““… both adds “csrf” and opts out of it””
✖ POST /api/import both adds "csrf" and opts out of it (route).
→ Remove one of the two declarations. An opt-out can only remove middleware the route inherits from a group.

Why: the same route says .middleware('csrf') and .withoutMiddleware('csrf'). Strutvane won’t guess which one you meant, because guessing could silently remove a protection. Fix: keep one of the two.

Section titled “A signed link answers 403 “invalid_signature””

Why: something changed the URL after it was signed: an email client that re-encoded it, a parameter added by hand, or a different APP_KEY on the server that checks it. Fix: send the link exactly as url.signedRoute() returned it, and make sure every server shares the same APP_KEY (after key:rotate, the old key stays valid through APP_PREVIOUS_KEYS).

✖ "Posts" is not a valid resource name.
→ Use the plural, lower-case table-style name, for example Route.resource('posts', PostController).