Skip to main content

Overview

ConvexReactClient is a stateful client that loads reactive queries and executes mutations over a WebSocket connection to your Convex backend.

Constructor

Create a new ConvexReactClient instance to connect to your Convex deployment.
import { ConvexReactClient } from "convex/react";

const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL);

Parameters

address
string
required
The URL of your Convex deployment, typically provided by an environment variable. For example: https://small-mouse-123.convex.cloud
options
ConvexReactClientOptions
Optional configuration object for the client.

Methods

mutation

Execute a mutation function on the server.
const result = await convex.mutation(
  api.messages.send,
  { text: "Hello!", channel: "#general" }
);
mutation
FunctionReference<'mutation'>
required
A function reference for the public mutation to run, like api.dir1.dir2.filename.func.
args
object
An arguments object for the mutation. If omitted, the arguments will be {}.
options
MutationOptions
Returns: A promise of the mutation’s result.

action

Execute an action function on the server.
const summary = await convex.action(
  api.ai.generateSummary,
  { text: "Some long text..." }
);
action
FunctionReference<'action'>
required
A function reference for the public action to run, like api.dir1.dir2.filename.func.
args
object
An arguments object for the action. If omitted, the arguments will be {}.
Returns: A promise of the action’s result.

query

Fetch a query result once (not reactive).
const messages = await convex.query(
  api.messages.list,
  { channel: "#general" }
);
Most application code should subscribe to queries using the useQuery hook instead. This method fetches the query result once without establishing a subscription.
query
FunctionReference<'query'>
required
A function reference for the public query to run.
args
object
An arguments object for the query. If omitted, the arguments will be {}.
Returns: A promise of the query’s result.

watchQuery

Construct a watch on a Convex query function.
const watch = convex.watchQuery(api.messages.list, { channel: "#general" });
const unsubscribe = watch.onUpdate(() => {
  const result = watch.localQueryResult();
  console.log("Query updated:", result);
});
Most application code should not call this method directly. Instead use the useQuery hook.
query
FunctionReference<'query'>
required
A function reference for the public query to run.
args
object
An arguments object for the query. If omitted, the arguments will be {}.
options
WatchQueryOptions
Returns: A Watch object with methods:
  • onUpdate(callback) - Subscribe to query changes, returns unsubscribe function
  • localQueryResult() - Get the current result (or undefined if not available)
  • journal() - Get the current query journal

setAuth

Set the authentication token for subsequent queries and mutations.
convex.setAuth(
  async () => {
    const token = await fetchTokenFromAuthProvider();
    return token;
  },
  (isAuthenticated) => {
    console.log("Auth status changed:", isAuthenticated);
  }
);
fetchToken
AuthTokenFetcher
required
An async function returning the JWT-encoded OpenID Connect Identity Token. Should return null if the token cannot be retrieved.
onChange
(isAuthenticated: boolean) => void
A callback that will be called when the authentication status changes.

clearAuth

Clear the current authentication token if set.
convex.clearAuth();

connectionState

Get the current connection state between the client and the Convex backend.
const state = convex.connectionState();
console.log("Connected:", state.isWebSocketConnected);
Returns: A ConnectionState object with properties:
  • hasInflightRequests - Whether there are pending requests
  • isWebSocketConnected - Whether the WebSocket is connected
  • timeOfOldestInflightRequest - Date of oldest pending request or null
  • hasEverConnected - Whether the client has ever connected
  • connectionCount - Number of times the client has connected
  • connectionRetries - Number of failed connection attempts
  • inflightMutations - Number of mutations in flight
  • inflightActions - Number of actions in flight

subscribeToConnectionState

Subscribe to connection state changes.
const unsubscribe = convex.subscribeToConnectionState((state) => {
  console.log("Connection state:", state);
});

// Later, unsubscribe
unsubscribe();
callback
(connectionState: ConnectionState) => void
required
Function called whenever the connection state changes.
Returns: An unsubscribe function to stop listening.

close

Close any network handles associated with this client and stop all subscriptions.
await convex.close();
Returns: A promise fulfilled when the connection has been completely closed.

Properties

url

Return the address for this client.
const deploymentUrl = convex.url;
Returns: The Convex deployment URL as a string.
Not guaranteed to match the address used in the constructor as it may be canonicalized.

Example usage

Basic setup

import { ConvexReactClient } from "convex/react";
import { ConvexProvider } from "convex/react";

const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL);

function App() {
  return (
    <ConvexProvider client={convex}>
      <YourApp />
    </ConvexProvider>
  );
}

With authentication

import { ConvexReactClient } from "convex/react";
import { useAuth0 } from "@auth0/auth0-react";

const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL);

function AuthWrapper() {
  const { getAccessTokenSilently, isAuthenticated } = useAuth0();
  
  useEffect(() => {
    if (isAuthenticated) {
      convex.setAuth(async () => {
        return await getAccessTokenSilently();
      });
    } else {
      convex.clearAuth();
    }
  }, [isAuthenticated]);
  
  return <App />;
}

Build docs developers (and LLMs) love