An astronaut, on the moon, using a machine to create many clouds that obscure the sky.

    Self-host Triplit on Cloudflare Workers

    TLDR

    We release a guide for self-hosting Triplit on Cloudflare Workers and add new documentation for the Sessions API.

    Triplit on Cloudflare Worker in 30 lines of code

    With the release of our Hono implementation of the Triplit sync server, you can deploy your own implementation in about 30 lines of code. This is a great, low-cost way to run your own Triplit server without needing to manage infrastructure. It's also easy to expand your Worker to support multi-tenancy, e.g. spinning up a Durable Object per-user. Partitioning like this can be helpful, as Workers have memory constraints that may make them unsuitable for large standalone Triplit databases.

    Here's how to set up the simplest possible Triplit server on Cloudflare Workers:

    import { DurableObject } from 'cloudflare:workers';
    import { upgradeWebSocket } from '@triplit/server/cloudflare';
    import { createTriplitHonoServer } from '@triplit/server';
    import DurableObjectStore from '@triplit/db/storage/durable-object-tuple-store';
    
    export class MyDurableObject extends DurableObject {
      state: DurableObjectState;
      app: ReturnType<typeof createTriplitHonoServer>;
      constructor(ctx: DurableObjectState, env: Env) {
        super(ctx, env);
        this.state = ctx;
        // Create the Triplit server
        this.app = createTriplitHonoServer(
          {
            // add any configuration options here
            jwtSecret: env.JWT_SECRET,
            // this is the Triplit storage provider for Durable Objects
            storage: new DurableObjectStore(this.state.storage),
          },
          // inject the platform-specific WebSocket upgrade function
          upgradeWebSocket
        );
      }
    
      async fetch(request: Request) {
        return this.app.fetch(request);
      }
    }
    
    export default {
      async fetch(request, env, ctx): Promise<Response> {
        // Get the Durable Object ID (this is where you could easily add multi-tenancy)
        let id: DurableObjectId = env.MY_DURABLE_OBJECT.idFromName('triplitDB');
        let stub = env.MY_DURABLE_OBJECT.get(id);
    
        // Forward the request to the Durable Object
        return await stub.fetch(request);
      },
    } satisfies ExportedHandler<Env>;
    

    Just run npm create cloudflare@latest -- durable-object-starter and replace the contents of index.ts with the above code. Then add compatibility_flags = [ "nodejs_compat_v2" ] to your wrangler.toml. Finally, install @triplit/server and @triplit/db, and you're good to go!

    Further Session improvements documentation

    As a continuation of last week's Session API update, we've added a new section to the documentation that goes over the relevant methods in detail. We've made some minor changes to the API since last week, including more consistent configuration between the TriplitClient constructor and the startSession method, more graceful handling of expiring sessions, and more typing of the onSessionError callback.

    deleteAll for quick data cleanup

    We've added a new deleteAll method to the HttpClient class (and an associated /delete-all endpoint to the server) that allows you to delete all data associated with a single collection. This is useful for testing and development, as it allows you to quickly reset your database to a known state. It's intended to be for administrative use only, so it requires the Secret token to be passed in to the HttpClient constructor (or in the request headers).

    Other improvements and bug fixes

    • Fixed a bug in the experimental entity cache that could cause simultaneous queries to return undefined results.
    • The /healthcheck endpoint should now be available for Triplit Cloud projects.