Access Durable Object RPC from Worker with Vite plugin

I have a worker and a durable object in a monorepo:

  • The worker is a tanstack-start app configured with the vite plugin.
  • The durable object facilitates a websocket connections and stores some state in SQLite.
I'm trying to set up a server function on the tanstack-start app to use the RPC functions defined in the durable object.

I have the DO referenced in my worker's wrangler.jsonc

    "durable_objects": {
        "bindings": [
            {
                "name": "MY_WS_DO",
                "class_name": "WsDo",
                "script_name": "ws-do",
            },
        ],
    },


I tried using the global env import:

import {env} from 'cloudflare:workers'
import {createServerFn} from '@tanstack/react-start'
import * as v from 'valibot'

export const myServerFn = createServerFn({method: 'POST'})
    .inputValidator((data: unknown) =>
        v.parse(v.object({name: v.string()}), data),
    )
    .handler(async ({data: {name}}) => {
        const doId = env.MY_WS_DO.idFromName(name)
        const stub = env.MY_WS_DO.get(doId)
        const res = await stub.myRPCfn()

        return res
    })


But "Workers do not allow I/O from outside a request context" so that won't work.

(The actual error I get is: Couldn't find the durable Object "WsDo" of script "ws-do" I can confirm that I am able to access the stub and can console.log the name and id of the DO, but using service bindings does not work in this context)

But I'm not sure how to access the request context from within a vite-configured worker.

I'm also not sure that's the right way to go about this.

Should I be accessing env a different way? Should I define the DO as an auxiliary worker in the vite plugin?
Was this page helpful?