`\n\n2. The entrypoint on the server will be `lib/main.dart` or the file specified using the `-i (--input)` option when\n running `jaspr serve` or `jaspr build`.\n\n## ๐Ÿ’ฝ Loading Data on the Server\n\nWhen using server side rendering, you want the ability to load some data asychrously before rendering the components.\nWith `jaspr` this is build into the framework and easy to do.\n\nStart by using the `PreloadStateMixin` on a `StatefulComponent`s `State` class and implement the `Future preloadState()` method.\n\n```dart\nclass MyState extends State with PreloadStateMixin {\n \n @override\n Future preloadState() async {\n ...\n }\n}\n```\n\nThis method will only be executed on the server and will be called before `initState()`. It will defer\n`initState()` as well as building the component until the future returned by the method is completed.\n\n\nWhile it is only executed on the server it still will be compiled for the client, since Dart does not have\nselective compilation. So you have to make sure it will compile on the client, e.g. by using service locators\nand providing mock services on the client. (**TODO**: More explanation and How To)\n\n\n\nThis is a great use-case for jasprs [platform-specific imports](/advanced/imports)\n\n\n## โ™ป๏ธ Syncing Data to the Client\n\nAlongside with preloading some data on the server, you often want to also sync the data with the client.\nYou can simply add the `SyncStateMixin` which will automatically sync state from the server with the client.\n\nThe `SyncStateMixin` accepts a second type argument for the data type that you want to sync. You then have to\nimplement the `getState` and `updateState()` methods.\n\n```dart\nclass MyState extends State with SyncStateMixin {\n\n MyStateModel? model;\n \n // a globally unique id that is used to identify the state\n @override\n String get syncId => 'my_id';\n\n // this will get the state to be sent to the client\n // and is only executed on the server\n @override\n MyStateModel? getState() {\n return model;\n }\n\n // this will receive the state on the client\n // and it is safe to call setState\n void updateState(MyStateModel? value) {\n setState(() {\n model = value;\n });\n }\n}\n```\n\nIn order to send the data, it needs to be serialized on the server and deserialized on the client.\nThe serialization format is defined by the `syncCodec` getter defined in `SyncStateMixin`.\n\nThe codec must encode to a primitive or object value of one of the supported types: `Null, bool,\ndouble, int, Uint8List, String, Map, List`. By default, the codec is null and your state must\nalready be one of the supported types.\n\nWhen you want to use another type like a custom model class, you have to override the `syncCodec` getter, which\nhas to return a `Codec` that encodes to `String`. This can be any codec, however a typical use would be to\nencode your model to `Map` and the fuse this with the json codec to get a json string.\n\n```dart\n\nclass MyState extends State with SyncStateMixin {\n\n @override\n Codec get syncCodec => MyStateModelCodec();\n\n ...\n}\n\n// codec that encodes a value of MyStateModel to Map\nclass MyStateModelCodec extends Codec> {\n \n ...\n \n}\n```\n","headings":[{"id":"-loading-data-on-the-server","title":"๐Ÿ’ฝ Loading Data on the Server","rank":2},{"id":"๏ธ-syncing-data-to-the-client","title":"โ™ป๏ธ Syncing Data to the Client","rank":2}],"frontmatter":{"title":"Jaspr Server-Side Rendering","description":"How to setup server-side rendering and sync data between server and client in Jaspr.","previous":"/core/styling","next":"/core/ssg"},"code":"/*@jsxRuntime automatic @jsxImportSource react*/\nconst {Fragment: _Fragment, jsx: _jsx, jsxs: _jsxs} = arguments[0];\nfunction _createMdxContent(props) {\n const _components = Object.assign({\n section: \"section\",\n h1: \"h1\",\n p: \"p\",\n strong: \"strong\",\n ol: \"ol\",\n li: \"li\",\n code: \"code\",\n h2: \"h2\",\n span: \"span\",\n pre: \"pre\",\n a: \"a\"\n }, props.components), {Warning, Info} = _components;\n if (!Info) _missingMdxReference(\"Info\", true);\n if (!Warning) _missingMdxReference(\"Warning\", true);\n return _jsxs(_Fragment, {\n children: [_jsxs(_components.section, {\n id: \"-server-side-rendering\",\n children: [_jsx(_components.h1, {\n id: \"-server-side-rendering\",\n children: \"๐Ÿ— Server Side Rendering\"\n }), \"\\n\", _jsxs(_components.p, {\n children: [_jsx(_components.strong, {\n children: \"Jaspr\"\n }), \" is built to be server-side-rendering first. It leverages the power of Darts\\ncross-compilation to both js and native executables to execute the same app on the server and client.\"]\n }), \"\\n\", _jsx(_components.p, {\n children: \"For each target (server and client) you need to have a separate entrypoint to start your app. However\\ndepending on what project setup you choose, the web entrypoint might be automatically generated for you.\"\n }), \"\\n\", _jsxs(_components.ol, {\n children: [\"\\n\", _jsxs(_components.li, {\n children: [\"\\n\", _jsxs(_components.p, {\n children: [\"The entrypoint on the web will always be the corresponding file inside the \", _jsx(_components.code, {\n children: \"web\"\n }), \" directory,\\nusually \", _jsx(_components.code, {\n children: \"web/main.dart\"\n }), \". This file will be compiled to js and is included in the \", _jsx(_components.code, {\n children: \"index.html\"\n }), \" file\\nas a script: \", _jsx(_components.code, {\n children: \"\"\n })]\n }), \"\\n\"]\n }), \"\\n\", _jsxs(_components.li, {\n children: [\"\\n\", _jsxs(_components.p, {\n children: [\"The entrypoint on the server will be \", _jsx(_components.code, {\n children: \"lib/main.dart\"\n }), \" or the file specified using the \", _jsx(_components.code, {\n children: \"-i (--input)\"\n }), \" option when\\nrunning \", _jsx(_components.code, {\n children: \"jaspr serve\"\n }), \" or \", _jsx(_components.code, {\n children: \"jaspr build\"\n }), \".\"]\n }), \"\\n\"]\n }), \"\\n\"]\n }), \"\\n\"]\n }), _jsxs(_components.section, {\n id: \"-loading-data-on-the-server\",\n children: [_jsxs(_components.h2, {\n id: \"-loading-data-on-the-server\",\n children: [_jsx(_components.span, {\n role: \"img\",\n \"aria-label\": \"computer disk\",\n children: \"๐Ÿ’ฝ\"\n }), \" Loading Data on the Server\"]\n }), \"\\n\", _jsxs(_components.p, {\n children: [\"When using server side rendering, you want the ability to load some data asychrously before rendering the components.\\nWith \", _jsx(_components.code, {\n children: \"jaspr\"\n }), \" this is build into the framework and easy to do.\"]\n }), \"\\n\", _jsxs(_components.p, {\n children: [\"Start by using the \", _jsx(_components.code, {\n children: \"PreloadStateMixin\"\n }), \" on a \", _jsx(_components.code, {\n children: \"StatefulComponent\"\n }), \"s \", _jsx(_components.code, {\n children: \"State\"\n }), \" class and implement the \", _jsx(_components.code, {\n children: \"Future preloadState()\"\n }), \" method.\"]\n }), \"\\n\", _jsx(_components.pre, {\n raw: \"class MyState extends State with PreloadStateMixin {\\n \\n @override\\n Future preloadState() async {\\n ...\\n }\\n}\\n\",\n language: \"dart\",\n html: \"
class MyState extends State<MyStatefulComponent> with PreloadStateMixin {\\n  \\n  @override\\n  Future<void> preloadState() async {\\n    ...\\n  }\\n}\\n
\",\n children: _jsx(_components.code, {\n className: \"language-dart\",\n children: \"class MyState extends State with PreloadStateMixin {\\n \\n @override\\n Future preloadState() async {\\n ...\\n }\\n}\\n\"\n })\n }), \"\\n\", _jsxs(_components.p, {\n children: [\"This method will only be executed on the server and will be called before \", _jsx(_components.code, {\n children: \"initState()\"\n }), \". It will defer\\n\", _jsx(_components.code, {\n children: \"initState()\"\n }), \" as well as building the component until the future returned by the method is completed.\"]\n }), \"\\n\", _jsx(Warning, {\n children: _jsxs(_components.p, {\n children: [\"While it is only executed on the server it still will be compiled for the client, since Dart does not have\\nselective compilation. So you have to make sure it will compile on the client, e.g. by using service locators\\nand providing mock services on the client. (\", _jsx(_components.strong, {\n children: \"TODO\"\n }), \": More explanation and How To)\"]\n })\n }), \"\\n\", _jsx(Info, {\n children: _jsxs(_components.p, {\n children: [\"This is a great use-case for jasprs \", _jsx(_components.a, {\n href: \"/advanced/imports\",\n children: \"platform-specific imports\"\n })]\n })\n }), \"\\n\"]\n }), _jsxs(_components.section, {\n id: \"๏ธ-syncing-data-to-the-client\",\n children: [_jsxs(_components.h2, {\n id: \"๏ธ-syncing-data-to-the-client\",\n children: [_jsx(_components.span, {\n role: \"img\",\n \"aria-label\": \"recycling symbol\",\n children: \"โ™ป๏ธ\"\n }), \" Syncing Data to the Client\"]\n }), \"\\n\", _jsxs(_components.p, {\n children: [\"Alongside with preloading some data on the server, you often want to also sync the data with the client.\\nYou can simply add the \", _jsx(_components.code, {\n children: \"SyncStateMixin\"\n }), \" which will automatically sync state from the server with the client.\"]\n }), \"\\n\", _jsxs(_components.p, {\n children: [\"The \", _jsx(_components.code, {\n children: \"SyncStateMixin\"\n }), \" accepts a second type argument for the data type that you want to sync. You then have to\\nimplement the \", _jsx(_components.code, {\n children: \"getState\"\n }), \" and \", _jsx(_components.code, {\n children: \"updateState()\"\n }), \" methods.\"]\n }), \"\\n\", _jsx(_components.pre, {\n raw: \"class MyState extends State with SyncStateMixin {\\n\\n MyStateModel? model;\\n \\n // a globally unique id that is used to identify the state\\n @override\\n String get syncId => 'my_id';\\n\\n // this will get the state to be sent to the client\\n // and is only executed on the server\\n @override\\n MyStateModel? getState() {\\n return model;\\n }\\n\\n // this will receive the state on the client\\n // and it is safe to call setState\\n void updateState(MyStateModel? value) {\\n setState(() {\\n model = value;\\n });\\n }\\n}\\n\",\n language: \"dart\",\n html: \"
class MyState extends State<MyStatefulComponent> with SyncStateMixin<MyStatefulComponent, MyStateModel> {\\n\\n  MyStateModel? model;\\n  \\n  // a globally unique id that is used to identify the state\\n  @override\\n  String get syncId => 'my_id';\\n\\n  // this will get the state to be sent to the client\\n  // and is only executed on the server\\n  @override\\n  MyStateModel? getState() {\\n    return model;\\n  }\\n\\n  // this will receive the state on the client\\n  // and it is safe to call setState\\n  void updateState(MyStateModel? value) {\\n    setState(() {\\n      model = value;\\n    });\\n  }\\n}\\n
\",\n children: _jsx(_components.code, {\n className: \"language-dart\",\n children: \"class MyState extends State with SyncStateMixin {\\n\\n MyStateModel? model;\\n \\n // a globally unique id that is used to identify the state\\n @override\\n String get syncId => 'my_id';\\n\\n // this will get the state to be sent to the client\\n // and is only executed on the server\\n @override\\n MyStateModel? getState() {\\n return model;\\n }\\n\\n // this will receive the state on the client\\n // and it is safe to call setState\\n void updateState(MyStateModel? value) {\\n setState(() {\\n model = value;\\n });\\n }\\n}\\n\"\n })\n }), \"\\n\", _jsxs(_components.p, {\n children: [\"In order to send the data, it needs to be serialized on the server and deserialized on the client.\\nThe serialization format is defined by the \", _jsx(_components.code, {\n children: \"syncCodec\"\n }), \" getter defined in \", _jsx(_components.code, {\n children: \"SyncStateMixin\"\n }), \".\"]\n }), \"\\n\", _jsxs(_components.p, {\n children: [\"The codec must encode to a primitive or object value of one of the supported types: \", _jsx(_components.code, {\n children: \"Null, bool, double, int, Uint8List, String, Map, List\"\n }), \". By default, the codec is null and your state must\\nalready be one of the supported types.\"]\n }), \"\\n\", _jsxs(_components.p, {\n children: [\"When you want to use another type like a custom model class, you have to override the \", _jsx(_components.code, {\n children: \"syncCodec\"\n }), \" getter, which\\nhas to return a \", _jsx(_components.code, {\n children: \"Codec\"\n }), \" that encodes to \", _jsx(_components.code, {\n children: \"String\"\n }), \". This can be any codec, however a typical use would be to\\nencode your model to \", _jsx(_components.code, {\n children: \"Map\"\n }), \" and the fuse this with the json codec to get a json string.\"]\n }), \"\\n\", _jsx(_components.pre, {\n raw: \"\\nclass MyState extends State with SyncStateMixin {\\n\\n @override\\n Codec get syncCodec => MyStateModelCodec();\\n\\n ...\\n}\\n\\n// codec that encodes a value of MyStateModel to Map\\nclass MyStateModelCodec extends Codec> {\\n \\n ...\\n \\n}\\n\",\n language: \"dart\",\n html: \"
\\nclass MyState extends State<MyStatefulComponent> with SyncStateMixin<MyStatefulComponent, MyStateModel> {\\n\\n  @override\\n  Codec<MyStateModel, String> get syncCodec => MyStateModelCodec();\\n\\n  ...\\n}\\n\\n// codec that encodes a value of MyStateModel to Map<String, dynamic>\\nclass MyStateModelCodec extends Codec<MyStateModel, Map<String, dynamic>> {\\n  \\n  ...\\n  \\n}\\n
\",\n children: _jsx(_components.code, {\n className: \"language-dart\",\n children: \"\\nclass MyState extends State with SyncStateMixin {\\n\\n @override\\n Codec get syncCodec => MyStateModelCodec();\\n\\n ...\\n}\\n\\n// codec that encodes a value of MyStateModel to Map\\nclass MyStateModelCodec extends Codec> {\\n \\n ...\\n \\n}\\n\"\n })\n })]\n })]\n });\n}\nfunction MDXContent(props = {}) {\n const {wrapper: MDXLayout} = props.components || ({});\n return MDXLayout ? _jsx(MDXLayout, Object.assign({}, props, {\n children: _jsx(_createMdxContent, props)\n })) : _createMdxContent(props);\n}\nreturn {\n default: MDXContent\n};\nfunction _missingMdxReference(id, component) {\n throw new Error(\"Expected \" + (component ? \"component\" : \"object\") + \" `\" + id + \"` to be defined: you likely forgot to import, pass, or provide it.\");\n}\n"},"preview":false}

๐Ÿ— Server Side Rendering

Jaspr is built to be server-side-rendering first. It leverages the power of Darts cross-compilation to both js and native executables to execute the same app on the server and client.

For each target (server and client) you need to have a separate entrypoint to start your app. However depending on what project setup you choose, the web entrypoint might be automatically generated for you.

  1. The entrypoint on the web will always be the corresponding file inside the web directory, usually web/main.dart. This file will be compiled to js and is included in the index.html file as a script: <script defer src="main.dart.js"></script>

  2. The entrypoint on the server will be lib/main.dart or the file specified using the -i (--input) option when running jaspr serve or jaspr build.

๐Ÿ’ฝ Loading Data on the Server

When using server side rendering, you want the ability to load some data asychrously before rendering the components. With jaspr this is build into the framework and easy to do.

Start by using the PreloadStateMixin on a StatefulComponents State class and implement the Future<T> preloadState() method.

class MyState extends State<MyStatefulComponent> with PreloadStateMixin {
  
  @override
  Future<void> preloadState() async {
    ...
  }
}

This method will only be executed on the server and will be called before initState(). It will defer initState() as well as building the component until the future returned by the method is completed.

While it is only executed on the server it still will be compiled for the client, since Dart does not have selective compilation. So you have to make sure it will compile on the client, e.g. by using service locators and providing mock services on the client. (TODO: More explanation and How To)

This is a great use-case for jasprs platform-specific imports

โ™ป๏ธ Syncing Data to the Client

Alongside with preloading some data on the server, you often want to also sync the data with the client. You can simply add the SyncStateMixin which will automatically sync state from the server with the client.

The SyncStateMixin accepts a second type argument for the data type that you want to sync. You then have to implement the getState and updateState() methods.

class MyState extends State<MyStatefulComponent> with SyncStateMixin<MyStatefulComponent, MyStateModel> {

  MyStateModel? model;
  
  // a globally unique id that is used to identify the state
  @override
  String get syncId => 'my_id';

  // this will get the state to be sent to the client
  // and is only executed on the server
  @override
  MyStateModel? getState() {
    return model;
  }

  // this will receive the state on the client
  // and it is safe to call setState
  void updateState(MyStateModel? value) {
    setState(() {
      model = value;
    });
  }
}

In order to send the data, it needs to be serialized on the server and deserialized on the client. The serialization format is defined by the syncCodec getter defined in SyncStateMixin.

The codec must encode to a primitive or object value of one of the supported types: Null, bool, double, int, Uint8List, String, Map, List. By default, the codec is null and your state must already be one of the supported types.

When you want to use another type like a custom model class, you have to override the syncCodec getter, which has to return a Codec that encodes to String. This can be any codec, however a typical use would be to encode your model to Map<String, dynamic> and the fuse this with the json codec to get a json string.


class MyState extends State<MyStatefulComponent> with SyncStateMixin<MyStatefulComponent, MyStateModel> {

  @override
  Codec<MyStateModel, String> get syncCodec => MyStateModelCodec();

  ...
}

// codec that encodes a value of MyStateModel to Map<String, dynamic>
class MyStateModelCodec extends Codec<MyStateModel, Map<String, dynamic>> {
  
  ...
  
}