Build a full-stack feature with Cratis
By the end of this Cratis Platform tutorial, you can register an author and see their name appear in a live React list without refreshing, once projection processing catches up. The view comes from a recorded AuthorRegistered event, so you can follow the fact behind the displayed author.
You build that flow with Cratis Arc handling the command, Cratis Chronicle recording the event and deriving the author list as a read model, a view shaped for the screen, and Cratis Components supplying the command dialog. The screen calls the backend through generated TypeScript proxies rather than a hand-written API wrapper. Together, the command, event, read model, query, and screen form a vertical slice: the code for one behavior kept together.
Choose C#, Kotlin, Java, or TypeScript for the backend. The TypeScript backend is published on npm at 1.0.0 but has no scaffold yet, so you start it from a sample. The table below explains the backend differences; do not assume the implementations have identical capabilities.
First projection follows book events into a read model with TypeScript, Elixir, and C# examples. That journey stops before HTTP and React. Here, you build the later API/UI slice in a different domain: library authors. For the C# path, trace the command and event in step 3, the read model and query in step 4, and the dialog and screen in step 5.
Keep the feature under one module so you can navigate by behavior rather than technical layer. The event model below is a map of what you will implement. Read it from left to right: the user acts on a screen, a command records a fact, that fact produces a read model, and the next screen reads it:
Frames 01–03 show the command pattern: intent → fact. Frames 03–05 show the view pattern: fact → read model → screen. In code, Components owns the ui screens, Arc owns the cmd command and the query for the rmo read model, and Chronicle stores the evt event and derives the read model. The backend build generates the typed proxies that connect it to React. Pick a backend language in the tabs below; your selection follows you through the steps.
Before you start
Section titled “Before you start”Start the backend and frontend for one language before adding the author feature. Use the matching setup below; the steps that follow assume that host is in place.
Before running docker compose up, check the generated docker-compose.yml (or Samples/Library/docker-compose.yml for TypeScript). The current templates and Library sample bind published ports to loopback, for example "127.0.0.1:35000:35000". If your copy has mappings without a host IP, override them by replacing each mapping with a loopback-bound one: "35000:35000" becomes "127.0.0.1:35000:35000". Keep the existing host and container port numbers for every service, including the database and dashboard; for example, "4317:18889" becomes "127.0.0.1:4317:18889". Replace the original mappings rather than adding a second set. Run docker compose config (with -f Samples/Library/docker-compose.yml for TypeScript) and confirm every published port has host_ip: 127.0.0.1 before starting containers.
Install the .NET 11 template and run dotnet new cratis -o Library. The buildable Capstone sample contains this exact slice. From Library/, run docker compose up -d, dotnet build, then dotnet run. Start the Vite frontend with the package manager selected by your scaffold (for example, npm run dev).
For brevity, the C# slice keeps its four types (AuthorId, RegisterAuthor, AuthorRegistered, Author) in one Authors/ folder at the project root; the generated proxies land beside them, which is why the screen below imports ./RegisterAuthor and ./Author.
Kotlin or Java
Section titled “Kotlin or Java”Use the Cratis CLI to run cratis new cratis --language kotlin -o Library or cratis new cratis --language java -o Library. Its native macOS and Linux binaries do not require the .NET SDK; the Windows global-tool installation does. If you already have the .NET SDK and templates installed, dotnet new cratis --language Kotlin -o Library or dotnet new cratis --language Java -o Library is another route. With JDK 17 active, run docker compose up -d, ./gradlew build, then ./gradlew bootRun from Library/. Start the Vite frontend separately, following the generated Kotlin or Java README. The Gradle build generates the proxies under build/generated/arc-proxies/.
TypeScript from npm
Section titled “TypeScript from npm”There is no TypeScript scaffold yet. The Arc packages are published on npm at 1.0.0: install @cratis/platform to get Arc and Chronicle together, or add individual packages such as @cratis/arc.core and a host adapter (@cratis/arc.express, @cratis/arc.fastify or @cratis/arc.hono). Follow the Arc TypeScript Library sample as the reference layout: from the Arc.TypeScript repository root run yarn install, docker compose -f Samples/Library/docker-compose.yml up -d, then yarn workspace @cratis/arc.sample.library dev. The Chronicle integration (@cratis/arc.chronicle) remains bounded and experimental.
The TypeScript tabs mirror the sample’s Features/Authors/AuthorId.ts, AuthorName.ts, Registration/Registration.ts and Listing/Listing.ts, without its Librarian role, unique-name constraint and authorsPage query; AuthorName.ts adds the name validation. The sample builds its proxies beside each feature as *.proxy.ts; see its README for setup and the local-only development identity.
The scaffolded C# and JVM Compose configurations start a separate Chronicle server with the default MongoDB choice, which persists the projected read model. Keep the author id, command/event, and read model/query together in the feature, with the host supplying their runtime wiring. Layouts differ by language; follow the sample’s neighboring files for imports.
How the backends differ in this slice
Section titled “How the backends differ in this slice”Each backend follows the same feature flow, but its host registration, access defaults, and read-model implementation differ. Use this table when you reach the named step:
| Behavior | C# | Kotlin and Java | TypeScript |
|---|---|---|---|
| Host change (step 1) | None; the scaffold’s AddCratis host |
Add the author types to KnownClientArtifacts |
None; the Library sample’s host |
| Author id in the generated proxy (step 2) | Guid, from EventSourceId<Guid> |
Guid, from a UUID-backed concept |
Guid, from ConceptAs<Guid> |
| Anonymous callers (step 3) | Accepted; the command declares no authorization | Rejected by default; the author types carry @AllowAnonymous |
Accepted; the command declares no authorization |
| Read model (step 4) | Projection from the event, with AutoMap | Reducer keyed by the event’s source id | Projection from the event |
| Author list (step 4) | Live: re-renders when the projection changes | Live: observes the first page of 50 materialized instances; needs Chronicle 19.22.2 or later | Live: re-renders when the projection changes |
| Generated proxies (step 4) | dotnet build, beside the types in Authors/ |
./gradlew build, under build/generated/arc-proxies/ |
The sample’s build, as *.proxy.ts beside each feature |
1. Wire the host (backend)
Section titled “1. Wire the host (backend)”The host connects Arc to Chronicle and exposes generated command and query endpoints. The scaffolds and Library sample supply this wiring; find it before changing the feature. C# and TypeScript need no change: their tabs show the existing host for orientation. On Kotlin and Java, add the three author types to the scaffold’s KnownClientArtifacts in ChronicleConfiguration, so an executable jar registers them. Keep the scaffold’s existing imports and add imports for the author types. Keep its sink fallback too: a non-MongoDB --Database generates WellKnownSinkTypes.SQL there, not MONGODB.
var builder = WebApplication.CreateBuilder(args);
builder.AddCratis( configureArcBuilder: arcBuilder => arcBuilder.WithMongoDB(configureMongoDB: mongoBuilder => mongoBuilder.WithCamelCaseNamingPolicy()), configureChronicleBuilder: chronicleBuilder => chronicleBuilder.WithCamelCaseNamingPolicy());
builder.Services.AddControllers();builder.Services.AddMvc();builder.Services.AddEndpointsApiExplorer();builder.Services.AddSwaggerGen(options => options.AddConcepts());
var app = builder.Build();
app.UseRouting();
app.UseDefaultFiles();app.UseStaticFiles();
app.UseWebSockets();app.MapControllers();app.UseCratis();
app.UseSwagger();app.UseSwaggerUI();app.MapFallbackToFile("/index.html");
await app.RunAsync();import io.cratis.chronicle.ChronicleOptions;import io.cratis.chronicle.artifacts.IArtifactActivator;import io.cratis.chronicle.artifacts.KnownClientArtifacts;import io.cratis.chronicle.connection.ChronicleConnectionString;import io.cratis.chronicle.sinks.WellKnownSinkTypes;import io.cratis.chronicle.spring.ChronicleProperties;import java.util.List;import kotlin.jvm.JvmClassMappingKt;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)public class ChronicleConfiguration { @Bean public ChronicleOptions chronicleOptions( ChronicleProperties properties, IArtifactActivator artifactActivator, @Value("${spring.application.name:Unknown}") String applicationName ) { var artifacts = new KnownClientArtifacts(List.of( JvmClassMappingKt.getKotlinClass(Registered.class), JvmClassMappingKt.getKotlinClass(Listing.class), JvmClassMappingKt.getKotlinClass(ListingReducer.class), JvmClassMappingKt.getKotlinClass(RegistrationReactor.class), JvmClassMappingKt.getKotlinClass(AuthorRegistered.class), JvmClassMappingKt.getKotlinClass(Author.class), JvmClassMappingKt.getKotlinClass(AuthorReducer.class))); var sinkType = properties.getDefaultSinkTypeId(); if (sinkType == null) sinkType = System.getenv("CHRONICLE_SINK_TYPE"); if (sinkType == null) sinkType = WellKnownSinkTypes.MONGODB; var programIdentifier = properties.getProgramIdentifier() == null ? applicationName : properties.getProgramIdentifier(); return new ChronicleOptions( ChronicleConnectionString.Companion.parse(properties.getConnectionString()), programIdentifier, sinkType, properties.getAutoDiscoverAndRegister(), artifacts, artifactActivator); }}import io.cratis.chronicle.ChronicleOptionsimport io.cratis.chronicle.artifacts.IArtifactActivatorimport io.cratis.chronicle.artifacts.KnownClientArtifactsimport io.cratis.chronicle.connection.ChronicleConnectionStringimport io.cratis.chronicle.sinks.WellKnownSinkTypesimport io.cratis.chronicle.spring.ChroniclePropertiesimport org.springframework.beans.factory.annotation.Valueimport org.springframework.context.annotation.Beanimport org.springframework.context.annotation.Configuration
@Configuration(proxyBeanMethods = false)class ChronicleConfiguration { @Bean fun chronicleOptions( properties: ChronicleProperties, artifactActivator: IArtifactActivator, @Value("\${spring.application.name:Unknown}") applicationName: String ): ChronicleOptions = ChronicleOptions( connectionString = ChronicleConnectionString.parse(properties.connectionString), programIdentifier = properties.programIdentifier ?: applicationName, defaultSinkTypeId = properties.defaultSinkTypeId ?: System.getenv("CHRONICLE_SINK_TYPE") ?: WellKnownSinkTypes.MONGODB, autoDiscoverAndRegister = properties.autoDiscoverAndRegister, artifacts = KnownClientArtifacts( Registered::class, Listing::class, ListingReducer::class, RegistrationReactor::class, AuthorRegistered::class, Author::class, AuthorReducer::class ), artifactActivator = artifactActivator )}import express from 'express';import { ArcApplication } from '@cratis/arc.core';import { cratisArc } from '@cratis/arc.express';import { withChronicle } from '@cratis/arc.chronicle';import { metadata } from './Features/generatedMetadata.js';
const builder = ArcApplication.createBuilder({ development: true, nativePrincipal: true, tenancy: { resolve: () => 'Default' }, query: { allowedOrigins: ['http://127.0.0.1:5173'] } });builder.useGeneratedMetadata(metadata);withChronicle(builder, process.env.CHRONICLE_URL ? { connectionString: process.env.CHRONICLE_URL } : {});await builder.discover(new URL('./Features/', import.meta.url));const application = await builder.build();const host = express();// Demo-only trusted principal: never accept a role from an HTTP header.const demoIdentity = () => ({ principal: { id: 'demo-librarian', roles: ['Librarian'], isAuthenticated: true } });const arc = cratisArc(application, demoIdentity);host.use(arc);const port = Number(process.env.PORT ?? 3000);const listener = host.listen(port, '127.0.0.1', () => console.log(`Library listening on http://127.0.0.1:${port}`));const closeWebSockets = arc.injectWebSocket(listener, demoIdentity);const stop = async () => { await closeWebSockets(); await new Promise<void>((resolve, reject) => listener.close(error => error ? reject(error) : resolve())); await application.dispose();};process.once('SIGINT', () => { void stop().catch(error => { console.error(error); process.exitCode = 1; }); });process.once('SIGTERM', () => { void stop().catch(error => { console.error(error); process.exitCode = 1; }); });2. Identify the event stream (backend)
Section titled “2. Identify the event stream (backend)”Chronicle uses the command key to select the author’s event stream. Every backend backs AuthorId with a GUID, so the generated command proxy types the id as a Guid whichever backend you chose. In C#, AuthorId derives from EventSourceId<Guid>, which also makes it the read model’s key without a [Key] attribute:
public record AuthorId(Guid Value) : EventSourceId<Guid>(Value){ public static readonly AuthorId NotSet = new(Guid.Empty); public static implicit operator AuthorId(Guid value) => new(value); public static AuthorId New() => new(Guid.NewGuid());}import io.cratis.fundamentals.concepts.ConceptAs;import java.util.UUID;
public record AuthorId(UUID value) implements ConceptAs<UUID>, io.cratis.chronicle.concepts.ConceptAs<UUID> { @Override public UUID getValue() { return value; }}import io.cratis.fundamentals.concepts.ConceptAs as ArcConceptAsimport io.cratis.chronicle.concepts.ConceptAs as ChronicleConceptAsimport java.util.UUID
data class AuthorId(private val id: UUID) : ArcConceptAs<UUID>, ChronicleConceptAs<UUID> { override fun value(): UUID = id override val value: UUID get() = id
companion object { fun new(): AuthorId = AuthorId(UUID.randomUUID()) }}import { ConceptAs, Guid } from '@cratis/fundamentals';
export class AuthorId extends ConceptAs<Guid> { static readonly valueType = Guid; static create(): AuthorId { return new AuthorId(Guid.create()); }}3. Register the author (backend)
Section titled “3. Register the author (backend)”The command expresses intent; its handler returns the event that happened. Chronicle appends that event to the stream selected by the id. The Kotlin and Java command and read model carry @AllowAnonymous, as the scaffold’s own Register and Listing do, because Arc.Kotlin rejects anonymous callers by default and the JVM scaffolds have no sign-in:
[Command]public record RegisterAuthor(AuthorId Id, string Name){ public AuthorRegistered Handle() => new(Name);}
[EventType]public record AuthorRegistered(string Name);import io.cratis.arc.artifacts.Command;import io.cratis.arc.artifacts.CommandKey;import io.cratis.arc.authorization.AllowAnonymous;import io.cratis.chronicle.events.EventType;
@Command@AllowAnonymouspublic record RegisterAuthor(@CommandKey AuthorId id, String name) { public AuthorRegistered handle() { return new AuthorRegistered(name); }}
@EventTypepublic record AuthorRegistered(String name) { }import io.cratis.arc.artifacts.Commandimport io.cratis.arc.artifacts.CommandKeyimport io.cratis.arc.authorization.AllowAnonymousimport io.cratis.chronicle.events.EventType
@Command@AllowAnonymousdata class RegisterAuthor(@CommandKey val id: AuthorId, val name: String) { fun handle(): AuthorRegistered = AuthorRegistered(name)}
@EventTypedata class AuthorRegistered(val name: String = "")import { field } from '@cratis/fundamentals';import { eventType } from '@cratis/chronicle/events';import { command, key } from '@cratis/arc.core';import { AuthorId } from '../AuthorId.js';import { AuthorName } from '../AuthorName.js';
@eventType()export class AuthorRegistered { @field(AuthorName) name: AuthorName; constructor(name: AuthorName = new AuthorName('')) { this.name = name; }}
@command()export class RegisterAuthor { @key() @field(AuthorId) id!: AuthorId; @field(AuthorName) name!: AuthorName;
handle(): AuthorRegistered { return new AuthorRegistered(this.name); }}4. Build and query the author list (backend)
Section titled “4. Build and query the author list (backend)”The read model describes the list entry; the event feeds it, and a query exposes the list. C# and TypeScript declare a projection from the event; in C#, AutoMap matches AuthorRegistered.Name to Name. Kotlin and Java use a reducer keyed by the event context’s source id, rather than a model-bound event mapping:
[ReadModel][FromEvent<AuthorRegistered>]public record Author(AuthorId Id, string Name){ public static ISubject<IEnumerable<Author>> AllAuthors(IMongoCollection<Author> collection) => collection.Observe();}import io.cratis.arc.artifacts.FromServices;import io.cratis.arc.authorization.AllowAnonymous;import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.java.ReadModelsJavaBridge;import io.cratis.chronicle.observation.Reducer;import io.cratis.chronicle.IEventStore;import java.util.List;import java.util.concurrent.Flow;
@io.cratis.arc.artifacts.ReadModel@io.cratis.chronicle.readModels.ReadModel@AllowAnonymouspublic record Author(String id, String name) { public static Flow.Publisher<List<Author>> allAuthors(@FromServices IEventStore store) { return ReadModelsJavaBridge.observeMaterializedInstancesPublisher(store.getReadModels(), Author.class, 0, 50); }}
@Reducerpublic final class AuthorReducer { public Author registered(AuthorRegistered event, Author state, EventContext context) { return new Author(context.getEventSourceId(), event.name()); }}import io.cratis.arc.artifacts.FromServicesimport io.cratis.arc.artifacts.ReadModel as ArcReadModelimport io.cratis.arc.authorization.AllowAnonymousimport io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.observation.Reducerimport io.cratis.chronicle.readModels.ReadModel as ChronicleReadModelimport kotlinx.coroutines.flow.Flow
@ArcReadModel@ChronicleReadModel@AllowAnonymousdata class Author(val id: String = "", val name: String = "") { companion object { @JvmStatic fun allAuthors(@FromServices eventStore: IEventStore): Flow<List<Author>> = eventStore.readModels.materialized.observeInstances(Author::class, 0, 50) }}
@Reducerclass AuthorReducer { fun registered(event: AuthorRegistered, state: Author?, context: EventContext): Author = Author(id = context.eventSourceId, name = event.name)}import { field } from '@cratis/fundamentals';import { query, readModel, service } from '@cratis/arc.core';import { ChronicleReadModels } from '@cratis/arc.chronicle';import type { Observable } from 'rxjs';import { fromEvent } from '@cratis/chronicle/projections';import { AuthorRegistered } from '../Registration/Registration.js';import { AuthorId } from '../AuthorId.js';import { AuthorName } from '../AuthorName.js';
@readModel()@fromEvent(AuthorRegistered)export class Author { @field(AuthorId) id!: AuthorId; @field(AuthorName) name!: AuthorName;
@query({ observable: true }, service(ChronicleReadModels)) static allAuthors(models: ChronicleReadModels): Observable<Author[]> { return models.observeAll(Author, author => author.id.toString()); }}Build your backend now (dotnet build, ./gradlew build, or the Library sample’s yarn workspace @cratis/arc.sample.library build) to generate the TypeScript command and query proxies. After changing a backend property, regenerate those proxies and type-check the frontend to find incompatible typed usages. This checks the contract, not the running integration.
Chronicle processes projections asynchronously, so a successful command can return before the author appears in the list. On Kotlin and Java, allAuthors observes a page of materialized instances, as described in the table above.
5. Build the screen (frontend)
Section titled “5. Build the screen (frontend)”The screen below is the shared React flow from the compiled C# Capstone sample: run a generated command in a dialog, read a generated query, mount a route. Use the same Components with every backend, adjusting the generated proxy imports:
- C#: The snippets below import proxies co-located in
Authors/; the id in the command proxy is aGuid. - Kotlin and Java: Import
RegisterAuthor.tsandAllAuthors.tsunderbuild/generated/arc-proxies/via your scaffold’sApi/alias; the id in the command proxy is aGuid, as in C#.AllAuthorsis observable, so.use()re-renders when the new author is projected. It can take a moment to appear, because Chronicle projects asynchronously. - TypeScript: Import
RegisterAuthorfromFeatures/Authors/Registration/RegisterAuthor.proxy.tsandAllAuthorsfromFeatures/Authors/Listing/AllAuthors.proxy.ts; keepGuid.create()for its id. Its RegisterAuthorForm seeds the id before validation withinitialValues.
-
Create the command dialog in
AddAuthor.tsx.CommandDialoginstantiates and runs the generated command and renders the OK/Cancel footer; you supply the fields:import { CommandDialog } from '@cratis/components/CommandDialog';import { InputTextField } from '@cratis/components/CommandForm';import { RegisterAuthor } from './RegisterAuthor';import { Guid } from '@cratis/fundamentals';export const AddAuthor = () => (<CommandDialog<RegisterAuthor>command={RegisterAuthor}title="Add author"okLabel="Add"initialValues={{ id: Guid.create() }}><InputTextField<RegisterAuthor> value={i => i.name} title="Name" /></CommandDialog>); -
Create the list screen in
Authors.tsx. The generatedAllAuthorsproxy is observable:.use()re-renders when the projection changes. Kotlin and Java observe a page of materialized instances, as described in the table. Add a button to open the dialog:import { useDialog } from '@cratis/arc.react/dialogs';import { AllAuthors } from './Author';import { AddAuthor } from './AddAuthor';export const Authors = () => {const [AddAuthorDialog, showAddAuthor] = useDialog(AddAuthor);const [authors] = AllAuthors.use();return (<main><h1>Authors</h1><button type="button" onClick={() => { void showAddAuthor(); }}>Add author</button><ul>{authors.data.map(a => <li key={String(a.id)}>{a.name}</li>)}</ul><AddAuthorDialog /></main>);}; -
Mount the screen in the scaffold’s
App.tsx. ImportAuthorsfrom./Authors/Authorsand add this route inside the existing<Routes>, alongside/and/demo:<Route path='/authors' element={<Authors />} />Open
/authorsin the browser, choose Add author, and submit an author. Wait for projection processing, then check that the new name appears in the list without refreshing. If the command succeeds but the name does not appear:- Confirm that
AuthorRegisteredwas appended and that itsnamemaps to the author read model, following Chronicle’s empty or out-of-date read model checks. On Kotlin and Java, check the reducer’s mapping instead of a projection. - Check for observer failures in the Workbench or with
cratis chronicle diagnose; Chronicle diagnostics explains how to inspect observers and failed partitions. - In the browser’s Network panel, inspect the author query’s connection and incoming data for the submitted id and name. If the query receives the author but the list stays empty, inspect
authors.datain React. If no data arrives, use observable query diagnostics to checksubscribedandhasResultbefore changing the screen.
- Confirm that
Go deeper
Section titled “Go deeper”- C# backend: Commands and Queries in Arc, and the Cratis package that
AddCratisconfigures. - Kotlin and Java backend: the Chronicle guide for Arc.Kotlin.
- TypeScript backend: the Arc TypeScript Library sample.
- Every backend: Projections in Chronicle.
- Frontend: CommandDialog and data tables in Components.
- The reasoning: Why developers choose Cratis and Why Arc.