Connect-Query Documentation

repository·main·Indexed 18 days ago

https://github.com/connectrpc/connect-query-es

A TypeScript wrapper around TanStack Query that enables type-safe communication with servers using the Connect Protocol. It leverages Protobuf schemas to automatically infer types for queries and mutations. The library includes @connectrpc/connect-query for React hooks, @connectrpc/connect-query-core for fundamental logic, and @connectrpc/protoc-gen-connect-query for generating client code from Protobuf definitions.

Tokens
10.9K
Snippets
34
Records
60
Agent score
61%

What's inside Connect-Query

  1. Overview of @connectrpc/connect-query-core

    main
    The @connectrpc/connect-query-core package contains the fundamental logic for the Connect-Query API. It provides the non-hook functions required to integrate Connect RPC with various tanstack/query variants. While this package contains the core logic, the high-level React hooks (functions starting with use) are typically consumed via the @connectrpc/connect-query package.
  2. Generate RPC methods with protoc-gen-connect-query

    main

    While protoc-gen-es generates service objects, the protoc-gen-connect-query plugin provides an additional convenience by exporting every RPC method individually. This allows you to import methods directly (e.g., say) instead of accessing them through a service object (e.g., ElizaService.say).

    import { ElizaService } from "./eliza_pb";
    
    /**
     * Say is a unary RPC. Eliza responds to the prompt with a single sentence.
     *
     * @generated from rpc connectrpc.eliza.v1.ElizaService.Say
     */
    export const say: (typeof ElizaService)["method"]["say"];
  3. Understand Connect-Query generated output structure

    main

    Connect-Query generates one output file for every service defined in your proto files. This differs from @bufbuild/protoc-gen-es, which typically generates one file per proto file.

    Example structure: If you have pizza.proto containing DetroitStyleService and ChicagoStyleService, the output will be:

    • pizza_pb.ts (Generated by protoc-gen-es)
    • pizza-DetroitStyleService_connectquery.ts (Generated by protoc-gen-connect-query)
    • pizza-ChicagoStyleService_connectquery.ts (Generated by protoc-gen-connect-query)

    The *_pb.ts files are required dependencies for the *_connectquery.ts files.

  4. Connect-Query support for Streaming RPCs

    main
    Currently, Connect-Query only supports Unary RPC methods (request/response style). This design choice aligns with the paradigms of TanStack Query. Support for Server Streaming, Client Streaming, and Bidirectional Streaming is not yet implemented.
  5. Quickstart: Configure TransportProvider and QueryClient

    main

    To use Connect-Query, you must wrap your application in both a TransportProvider (from @connectrpc/connect-query) and a QueryClientProvider (from @tanstack/react-query). The TransportProvider requires a transport instance created via @connectrpc/connect-web.

    import { createConnectTransport } from "@connectrpc/connect-web";
    import { TransportProvider } from "@connectrpc/connect-query";
    import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
    
    const finalTransport = createConnectTransport({
      baseUrl: "https://demo.connectrpc.com",
    });
    
    const queryClient = new QueryClient();
    
    function App() {
      return (
        <TransportProvider transport={finalTransport}>
          <QueryClientProvider client={queryClient}>
            <YourApp />
          </QueryClientProvider>
        </TransportProvider>
      );
    }
  6. Install @connectrpc/protoc-gen-connect-query and runtime libraries

    main

    To use Connect-Query, you need to install both the code generator plugins and the runtime libraries. The generator works in tandem with @bufbuild/protoc-gen-es.

    Install the generator plugins as dev dependencies and the runtime libraries as regular dependencies:

    npm install --save-dev @connectrpc/protoc-gen-connect-query @bufbuild/protoc-gen-es
    npm install @connectrpc/connect-query @bufbuild/protobuf
  7. Test Connect-Query applications without network requests

    main
    You can test Connect-Query applications by using the createRouterTransport function from @connectrpc/connect. This creates a transport that simulates a backend, allowing you to run tests without making actual network requests. For end-to-end testing in Playwright, use the dedicated @connectrpc/connect-playwright package.
  8. Prefetch queries outside of React context

    main

    When you do not have access to React context (e.g., during server-side rendering or in utility functions), you can use createQueryOptions and provide a transport directly in the options object. This allows you to use standard TanStack Query methods like queryClient.prefetchQuery.

    import { say } from "./gen/eliza-ElizaService_connectquery";
    
    function prefetch() {
      return queryClient.prefetchQuery(
        createQueryOptions(say, { sentence: "Hello" }, { transport: myTransport }),
      );
    }
  9. Generate Connect-Query code with the buf CLI

    main

    The recommended way to generate code is using the buf CLI.

    1. Create a buf.gen.yaml configuration file in your project root:
    version: v2
    plugins:
      # Invokes protoc-gen-es to generate base types
      - local: protoc-gen-es
        out: src/gen
        opt: target=ts
      # Invokes protoc-gen-connect-query to generate Connect-Query clients
      - local: protoc-gen-connect-query
        out: src/gen
        opt: target=ts
    1. Run the generation command:
    npx @bufbuild/buf generate

    You can also add this to your package.json scripts for easier access:

    "scripts": {
        "buf:generate": "buf generate"
    }
    version: v2
    plugins:
      - local: protoc-gen-es
        out: src/gen
        opt: target=ts
      - local: protoc-gen-connect-query
        out: src/gen
        opt: target=ts