Custom Backend
How to use custom backends with Jaspr.
In the standard configuration, jaspr
creates its own http server to handle incoming requests and
render your components. For this it uses the popular shelf
package.
If you want, you can replace the server handling with your own backend setup. This allows also the use of your favorite dart backend framework.
Since jaspr
is built with shelf
, this works best when the backend framework is also compatible with shelf.
However you can work around this if that is not the case.
There are two main functions, that enable this:
Handler serveApp(AppHandler handler)
bundles everything jaspr does on the server into a custom shelf handler. The handler can then be passed to your backend or server implementation.String renderComponent(Component app)
directly renders the provided component into a html string.
When using your own backend setup, you can still do jaspr serve
, however auto-reload won't work
on the server automatically.
Shelf
shelf
is a widely-used package for building server apps with dart that is
maintained by the Dart team.
Shelf makes it easy to create and compose web servers and parts of web servers.
Since jaspr used shelf internally, it is pretty straightforward to built a custom backend for jaspr using shelf.
void main() async {
var handler = serveApp((request, render) {
// Optionally do something with `request`
print("Request uri is ${request.requestedUri}");
// Return a server-rendered response by calling `render()` with your root component
return render(App());
});
// provide `handler` to your app, e.g.
await shelf_io.serve(handler, InternetAddress.anyIPv4, 8080);
}
Check out our backend_shelf example to see this in action.
Make sure that you set the base path of your app when mounting the serveApp
handler to
any other route prefix than /
, otherwise your static resources like styles.css
or main.dart.js
can't be loaded correctly. Add the <base href="/<route_prefix>/">
tag to the head
of your
index.html
, as demonstrated in the example.
Serverpod
Serverpod is an open-source, scalable app server, written in Dart for the Flutter community. You can use Serverpod and Jaspr together using our official Serverpod Integration to build robust and scalable fullstack websites leveraging Serverpods builtin webserver and additional components.
To get started with combining Jaspr and Serverpod head over to the documentation of the integration package or checkout the example.
Dart Frog
dart_frog
is a new backend framework built by Very Good Ventures. You
can combine it with jaspr to build powerful fullstack web applications that use dart_frog for managing
the backend api and jaspr for rendering the frontend app.
Check out our backend_dart_frog example to see this in action.
With this, a dart_frog
route that renders a jaspr component can be as simple as:
Future<Response> onRequest(RequestContext context) {
return renderJasprComponent(context, MyComponent());
}