Skip to content

Response

A controller returns a value, and Dox turns it into the response for the client.

Return a value

Return the value from your controller. Dox sends a string as text, and a map or a model as JSON:

Map<String, String> hello(DoxRequest req) {
  return <String, String>{'message': 'hello world!'};
}

Future<Blog?> show(int id) async {
  return Blog().find(id);
}

This is what the client gets for each type:

You return The client gets
a String the text
a Map or a List JSON
a model or a list of models JSON (from its generated writeJson(), or from toJson())
a serializer JSON (from toJson(), or from its @Serialize() code)
a DTO or a list of DTOs JSON (from its fields)
an object with writeJson() JSON, see Write the JSON yourself
a DateTime the ISO 8601 text
an IHttpException, like NotFoundHttpException() its status code and JSON: {"code": ..., "message": ...}
a File (from dart:io) the file, streamed
a Stream<List<int>> the bytes, streamed
a StreamFile or a DownloadableFile the file, streamed
response(...) full control: status, headers, cookies

The htmlStrings flag sends a string as HTML. See Core flags.

Errors

Throw or return an exception to answer with an error:

throw NotFoundHttpException(message: 'Blog not found');

The client gets 404 with {"code":"not_found","message":"Blog not found"}. Each exception takes message: and errorCode:. A map message is sent as it is.

Exception Status
BadRequestException() 400
ForbiddenHttpException() 403
NotFoundHttpException() 404
MethodNotAllowedHttpException(allow) 405
PayloadTooLargeException() 413
UnsupportedMediaTypeException() 415
TokenMismatchException() 419
ValidationException() 422
TooManyRequestsException() 429
InternalErrorException() 500
QueryException() 500

See HTTP exceptions for all of them.

Any status

Stop the request with any status, an optional message and headers:

if (post.userId != req.auth?.id()) abort(403);
throw HttpStatusException(503,
    headers: <String, String>{'retry-after': '60'});

Your own exception

Extend IHttpException:

class PaymentRequiredException extends IHttpException {
  PaymentRequiredException({String message = 'Payment required'}) {
    super.code = HttpStatus.paymentRequired;
    super.errorCode = 'payment_required';
    super.message = message;
  }
}

Any other error gets 500, and goes to the exception handler.

Files and big responses

Return a File or a Stream<List<int>> to send a file. Dox sends it in chunks:

Route.get('/video', (DoxRequest req) => File('storage/video.mp4'));

A file gets the right Content-Type and Content-Length. It also answers Range requests with 206, so video players can seek and downloads can resume.

A stream with a type

Send a stream with its content type, or as a download with a file name:

return StreamFile(ContentType.parse('image/png'), bytes, length: size);
return DownloadableFile(ContentType.binary, bytes, 'report.pdf');

Files from storage

Make the browser save a file from File Storage:

Future<DownloadableFile> download(DoxRequest req) async {
  return Storage().download('report.pdf');
}

Show the file in the browser:

Future<StreamFile> show(DoxRequest req) async {
  return Storage().stream('photo.jpg');
}

The response() helper

Set the status, headers or cookies. All methods return the response, so you can chain them:

DoxResponse store(DoxRequest req) {
  return response(<String, String>{'status': 'created'})
      .statusCode(201)
      .header('X-Request-Id', 'abc')
      .contentType(ContentType.json);
}

Setting the status

Set the status code. The default is 200:

response(data).statusCode(201);

Setting headers

Set one header. If a middleware already set it, the new value is added. Pass replace: true to replace it:

response(data).header('X-Key', 'value');
response(data).header('X-Key', 'value', replace: true);

The replaceHeaders flag makes header replace by default. See Core flags.

Set many headers. Each key replaces the header with the same name:

response(data).withHeaders(<String, String>{'X-One': '1', 'X-Two': '2'});

Set the content type. ContentType is from dart:io:

response(html).contentType(ContentType.html);

Caching

Set Cache-Control. Duration(minutes: 5) sends max-age=300:

response(data).cache(Duration(minutes: 5));

Changing the body

Change the body, or send a byte stream as the body:

response('').content(value);
response('').stream(byteStream);

Sending encoded bytes

When the text is already UTF-8 bytes, for example a rendered page, pass the bytes. Dox sends them as they are and does not encode them again:

response('').contentBytes(utf8.encode('<p>Hello</p>'));

The body gets the same content type as a String body, and getContent() gives the text.

Reading the response

Read the body, the status and the headers, for example in a middleware. A null status means 200:

res.getContent();
res.status;
res.headers;

Reading the body as bytes

Read a text body as UTF-8 bytes, for example to hash it with no decode. The result is null when the body is not text, like a map or a file:

Uint8List? bytes = res.getContentBytes();

Redirect

Send the browser to another page. The status is 302 by default:

return redirect('/login');
return redirect('/posts', status: 301);

Send the browser back to the page of the Referer header, for example after a form post. With no Referer, or one of another host, it goes to the fallback:

return back(req);
return back(req, fallback: '/home');

See Session for flash messages with a redirect.

Make a DoxCookie and add it to the response:

DoxCookie cookie = DoxCookie('theme', 'dark');
return response('ok').cookie(cookie);

Set the cookie options:

DoxCookie token = DoxCookie(
  'token',
  'value',
  maxAge: Duration(days: 7), // default 1 hour
  httpOnly: true, // default true: page scripts can not read it
  secure: true,   // default: only when the request came over https
  path: '/',
  sameSite: SameSite.lax, // from dart:io. default: none sent
);
return response('ok').cookie(token);

Delete a cookie:

return response('ok').cookie(DoxCookie('token', ''), setExpire: true);

Dox encrypts the cookie value with APP_KEY. If the browser or another app must read it, use DoxCookie(key, value, encrypt: false), and read it with req.cookie(key, decrypt: false). See Request: cookies.

To decrypt a raw cookie value with no request, use DoxCookie.decrypt(name, value).

Send the response yourself

Write the raw response, for example a stream with trailers. See Request: send the response yourself.

Change every response

Change every response in one place, for example to add a header. Set a responseHandler in AppConfig:

lib/app/http/handler.dart
class ResponseHandler extends ResponseHandlerInterface {
  @override
  DoxResponse handle(DoxResponse res) {
    return res.header('X-Powered-By', 'Dox');
  }
}
lib/config/app.dart
AppConfig appConfig = AppConfig(
  responseHandler: ResponseHandler(),
);

Write the JSON yourself

Most apps do not write this code. The generator writes it for a model, for a DTO and for a @Serialize() class. Write it yourself only for a class that the generator can not do.

Why Dox writes JSON this way

A toJson() method makes a Map for each response. Then the encoder reads the map, which has no types, and copies each value again. Thus each request makes more objects and gives more work to the garbage collector.

writeJson() writes the typed fields directly into the bytes of the response, in one pass, with no map. For a list of 40 models with two dates each, the encode time goes from 44 µs to 8 µs. A list of DTOs takes 2.8 µs. On the same data and machine, JSON.stringify of Bun takes 3.3 µs.

Implement JsonWritable

Implement JsonWritable in the class. Dox then calls writeJson(), and not toJson(), for a response:

class Item implements JsonWritable {
  Item(this.id, this.name);
  final int id;
  final String name;

  @override
  void writeJson(JsonWriter writer) {
    writer.startObject();
    writer.key('id');
    writer.integer(id);
    writer.key('name');
    writer.string(name);
    writer.endObject();
  }
}

The writer has these methods:

Method It writes
startObject() and endObject() { and }
key(name) the name of the next field
string(value) a text, or null
integer(value) a whole number, or null
dateTime(value) a date as ISO 8601 text, or null
boolean(value) true, false or null
value(value) any other value: a double, a List, a Map or an object

Write one value after each key(). The writer adds the commas.

The writer also has run(). It writes a fixed part of JSON with no check and no comma. The generated code of a DTO and of a @Serialize() class uses it. Do not use it in your own code: use key().

JSON.stringify() and jsonEncode() do not call writeJson(). If you use them with the class, also give it a toJson().

Next steps