TinyBase logoTinyBase β

authorize

The authorize method is used to decide whether a client may join the path that the Durable Object serves, and if so, how.

authorize(
  pathId: string,
  request: Request,
): ClientAccess | Promise<ClientAccess | undefined> | undefined
TypeDescription
pathIdstring

The Id of the path the client wishes to join.

requestRequest

The WebSocket upgrade request.

returnsClientAccess | Promise<ClientAccess | undefined> | undefined

A ClientAccess object, or undefined to refuse the client, or a Promise of either.

It is called with the Id of the path and the WebSocket upgrade request, from which you can read a token (from the URL query string, for example) or a cookie. Return a ClientAccess object to let the client join, or undefined to refuse it, in which case the upgrade request receives a 403 response. It can be asynchronous. If it throws, the client is refused.

The ClientAccess object is kept with the client's WebSocket, so it survives the Durable Object hibernating, and its serialized form should be no larger than Cloudflare's 2,048-byte attachment limit.

Overriding this method, or either of the canWriteCell and canWriteValue methods, makes the Durable Object's MergeableStore the only peer that its clients synchronize with, so that everything they read and write passes through it. If you do not also override the createPersister method, the Durable Object uses an in-memory MergeableStore, which does not survive the Durable Object being evicted.

Since this makes the fetch method asynchronous, remember to await the super implementation if you further override that too.

Example

This example lets staff write to the Durable Object's path, lets customers only read it, and refuses anyone else.

import {createMergeableStore} from 'tinybase';
import {createDurableObjectSqlStoragePersister} from 'tinybase/persisters/persister-durable-object-sql-storage';
import {WsServerDurableObject} from 'tinybase/synchronizers/synchronizer-ws-server-durable-object';

export class MyDurableObject extends WsServerDurableObject {
  createPersister() {
    return createDurableObjectSqlStoragePersister(
      createMergeableStore(),
      this.ctx.storage.sql,
    );
  }

  authorize(pathId, request) {
    const token = new URL(request.url).searchParams.get('token');
    return token == 'staff'
      ? {}
      : token == 'customer'
        ? {readOnly: true}
        : undefined;
  }
}

Since

v10.1.0