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.

Responses

View as Markdownllms.txt

Every action ends by returning a response: a status code (200 OK, 201 Created, 404 Not Found…), some headers, and a body. Strutvane responses are standard Web Response objects, the same ones fetch() returns, made easy with three helpers on ctx.

For errors, you don’t build a response at all: you throw an HTTP error, and Strutvane turns it into a consistent problem+json body.

routes/api.ts
Route.get('/ping', (ctx) => ctx.json({ pong: true })),
Terminal window
curl -i http://localhost:3000/api/ping

What you’ll see:

HTTP/1.1 200 OK
content-type: application/json
{"pong":true}
return ctx.json({ data: post }) // 200
return ctx.json({ data: post }, 201) // 201 Created
return ctx.json({ data: post }, 201, { location: route('posts.show', { post }) })
return ctx.json({ queued: true }, 202, { 'retry-after': '30' })

content-type: application/json is always set for you. Models are turned into JSON through their toJSON(), so hidden columns (like password or api_token) never appear.

When you create something, answer 201 and say where it lives:

app/http/controllers/note.controller.ts
async store(ctx: HttpContext): Promise<Response> {
const input = await new StoreNoteRequest().validate(ctx)
const note = await Note.create(input)
return ctx.json({ data: note }, 201, { location: route('notes.show', { note }) })
}

What you’ll see:

HTTP/1.1 201 Created
location: /api/notes/12
content-type: application/json
{"data":{"id":12,"text":"Buy milk", …}}

ResourceController’s store does this for you whenever a .show route exists for the resource.

Resource lists use one shape everywhere, so a client can page through any of them the same way:

{
"data": [{ "id": 1, "title": "Hello World" }],
"meta": { "page": 1, "perPage": 25, "total": 3, "lastPage": 1, "from": 1, "to": 3 }
}

Web routes return the React app’s HTML shell; React takes over in the browser:

app/http/controllers/spa.controller.ts
import { config, Controller, type HttpContext } from '@strutvane/framework'
export class SpaController extends Controller {
show(ctx: HttpContext): Response {
// The app name goes into HTML, so strip characters that could break out of the title.
const title = config('app.name').replace(/[<>&"]/g, '')
return ctx.html(`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title><script type="module" src="/build/app.js"></script></head><body><div id="root"></div></body></html>`)
}
}

content-type: text/html; charset=utf-8 is set for you. Escape anything dynamic you put into HTML.

For a successful delete, answer 204 No Content:

async destroy(ctx: HttpContext): Promise<Response> {
const post = ctx.model(Post)
await post.delete()
return ctx.noContent()
}
HTTP/1.1 204 No Content

ctx.json, ctx.html and ctx.noContent are shortcuts. Any standard Response works:

return new Response('id,title\n1,Hello World\n', {
headers: { 'content-type': 'text/csv; charset=utf-8', 'content-disposition': 'attachment; filename="posts.csv"' },
})

Use a plain Response and a set-cookie header. Mark cookies HttpOnly (JavaScript can’t read them), Secure (HTTPS only) and SameSite=Lax:

const response = ctx.json({ data: { theme: 'dark' } })
response.headers.append('set-cookie', 'theme=dark; Path=/; Max-Age=31536000; HttpOnly; Secure; SameSite=Lax')
return response

To send the browser to another page, return a redirect. Strutvane’s redirect() has three methods, so you always say whether you mean “my own page” or “another site”:

app/http/controllers/session.controller.ts
import { Controller, redirect, type HttpContext } from '@strutvane/framework'
export class SessionController extends Controller {
afterLogin(ctx: HttpContext): Response {
return redirect().intended(ctx, '/dashboard') // where they were going, or /dashboard
}
toPosts(): Response {
return redirect().to('/posts', 303) // one of your own paths
}
toBilling(): Response {
return redirect().away('https://billing.example.com/portal') // another site, on purpose
}
}

What you’ll see:

HTTP/1.1 303 See Other
location: /posts

to() and intended() accept only paths on your own site, so a crafted link (?intended=//evil.com) can’t turn your app into a springboard for phishing. intended() quietly falls back; to() throws, because an unsafe target there is a bug in your code. The default status is 302; pass 301, 303, 307 or 308 when you need another. See Helpers.

return ctx.download('storage/exports/posts.csv', 'posts.csv') // "Save as…" in the browser
return ctx.file('storage/reports/summary.pdf') // shown in the browser

Both will set a safe Content-Disposition header: the file name you give is cleaned, so a name like ../../etc/passwd or one with quotes and newlines can’t break the header or point at another file.

Coming in 0.3: streaming and server-sent events

Section titled “Coming in 0.3: streaming and server-sent events”
  • stream() sends a response in pieces as you produce them: a large CSV export without holding it all in memory.
  • eventStream() sends server-sent events (SSE): a one-way stream of messages to the browser over one long request, for progress bars and live feeds (Laravel’s response()->eventStream()).

Both will handle back-pressure (pausing when the client reads slowly) and stop when the client disconnects, so an abandoned tab doesn’t keep your server working. A standard ReadableStream in a plain Response already works today if you need it.

Strutvane doesn’t render HTML templates on the server. Pages are the React app (see Frontend); controllers answer JSON. ctx.html() is there for the app shell, small pages and emails’ previews, not for building your UI.

To stop with an error, throw an HTTP error. The exception handler turns it into a response, so the same error looks the same from every action, middleware and helper:

import { ForbiddenError, HttpError, NotFoundError } from '@strutvane/framework'
throw new NotFoundError('No post matches "hello".')
throw new ForbiddenError('You may not delete this post.')
throw new HttpError(409, 'conflict', 'Conflict', 'That slug is taken.')
Class Status code When
NotFoundError(detail, hint?) 404 not_found The route or record doesn’t exist
UnauthenticatedError(detail?) 401 unauthenticated Nobody is signed in (adds www-authenticate: Bearer)
ForbiddenError(detail, hint?) 403 forbidden Signed in, but not allowed
ValidationError(issues) 422 validation_failed Input failed validation
TooManyRequestsError(seconds) 429 too_many_requests Rate limited (adds retry-after)
HttpError(status, code, title, detail, extras?) any yours Everything else

Every error body is an RFC 9457 problem (a standard JSON shape for errors):

HTTP/1.1 404 Not Found
content-type: application/problem+json
{
"type": "https://strutvane.dev/problems/not_found",
"title": "Not found",
"status": 404,
"code": "not_found",
"detail": "No post matches \"hello\"."
}
Field Meaning
type A URL built from code
title A short, fixed summary of the kind of problem
status The HTTP status, repeated in the body
code A stable identifier your client can switch on
detail A sentence about this occurrence, for a person
issues Only for validation: one { path, field, code, message } per problem (see below)
hint Only in local debug mode: how a developer can fix it. Never sent in production

Each entry in issues says where the problem is in two ways, so clients can use whichever is easier:

{ "path": ["items", 0, "title"], "field": "items.0.title", "code": "too_small", "message": "Title must be at least 3 characters." }
Key Means
path The location as a list of keys and array positions (RFC-0003)
field The same location as one dotted string, handy for matching a form field
code A stable, lowercase snake_case code to switch on
message A sentence for a person

Every code in Strutvane, for problems and issues alike, is lowercase snake_case.

throw new HttpError(409, 'conflict', 'Conflict', 'That slug is taken.', {
headers: { 'retry-after': '5' },
hint: 'Pick another slug or let Strutvane generate one.',
})

The hint appears only when APP_DEBUG=true and APP_ENV is local or testing. See Error Handling.

When the client doesn’t want JSON (a browser on a web route), the same error is shown as a minimal HTML page with the status, title and detail.

For the three most common stops there’s a one-liner:

import { abort } from '@strutvane/framework'
abort(404, 'No such post.') // NotFoundError
abort(403) // ForbiddenError: "You are not allowed to do this."
abort(401) // UnauthenticatedError

Answering early from deep code: ResponseError

Section titled “Answering early from deep code: ResponseError”

Sometimes a check deep in your code has a whole response to send, not an error (a redirect, for example). Throw it wrapped in a ResponseError, and the handler sends it unchanged:

import { ResponseError } from '@strutvane/framework'
throw new ResponseError(new Response(null, { status: 302, headers: { location: '/login' } }))

Whatever you return (JSON, HTML, a 404, an error page), Strutvane adds the security headers on the way out: a Content-Security-Policy with this request’s nonce, X-Content-Type-Options: nosniff, a strict Referrer-Policy, Permissions-Policy, framing protection and, in production, HSTS. You don’t need to set them yourself. See Security Features.

“… returned nothing instead of a Response”

Section titled ““… returned nothing instead of a Response””
PostController@show returned nothing instead of a Response.
→ Return ctx.json(...), ctx.html(...) or ctx.noContent().

Fix: add return: return ctx.json({ data: post }).

Why: you threw a plain Error. Only HttpError and its subclasses become 4xx responses; anything else is treated as a bug.

Fix:

throw new NotFoundError('No report for that month.') // not: throw new Error('not found')

Why: you built the JSON by hand ({ ...post }) instead of letting the model serialise itself.

Fix: return the model (ctx.json({ data: post })); its toJSON() drops hidden columns.

“redirect().to() was given …, which is not a same-origin path”

Section titled ““redirect().to() was given …, which is not a same-origin path””
✖ redirect().to() was given "https://partner.example/page", which is not a same-origin path.
→ Use redirect().away(url) for a deliberate external redirect.

Fix: use redirect().away(url) when leaving your site is intended.

My header disappears or throws “immutable”

Section titled “My header disappears or throws “immutable””

Why: responses built by Response.json(), Response.redirect() or fetch() have read-only headers. Fix: copy first, then set: const copy = new Response(response.body, response).