TanStackT
TanStack6mo ago
10 replies
wispy-olive

How do I stop server code getting leaked to the client?

Hi, I have an util that should only be used by server code in orpc that leverages the crypto module, but based on my browser logs I am getting errors such as:
Uncaught (in promise) Error: Module "crypto" has been externalized for browser compatibility. Cannot access "crypto.createCipheriv" in client code
---
Uncaught (in promise) ReferenceError: Buffer is not defined


My router is currently set up this way:
import { os } from "@orpc/server";
import { portalRouter } from "./routes/portal";

const createRpcRouter = {
    healthCheck: os.handler(() => {
        return "OK";
    }),
    portal: portalRouter,
};

export const rpcRouter = createRpcRouter;

export type RpcRouter = typeof rpcRouter;


and my client:
const getORPCClient = createIsomorphicFn()
    .server(() =>
        createRouterClient(rpcRouter, {
            context: () => {
                const { headers } = getWebRequest();
                return {
                    headers,
                };
            },
        }),
    )
    .client((): RouterClient<RpcRouter> => {
        const link = new RPCLink({
            url: `${window.location.origin}/api/rpc`,
        });
        return createORPCClient(link);
    });

export const client: RouterClient<RpcRouter> = getORPCClient();

export const orpc = createTanstackQueryUtils(client);


I saw online that you could use the serverOnly() function to wrap the router to solve this but it provides an error:

import { serverOnly } from "@tanstack/react-start";
const createRpcRouter = serverOnly(() => ({
    healthCheck: os.handler(() => {
        return "OK";
    }),
    portal: portalRouter,
}));

Error: serverOnly() functions can only be called on the server!
Was this page helpful?