Skip to main content
The Next.js module provides helpers for integrating Convex with Next.js features including Server Components, Server Actions, and Route Handlers.

Installation

Setup

All exported functions use the NEXT_PUBLIC_CONVEX_URL environment variable by default. The npx convex dev command automatically sets this during local development.
.env.local

Server Components

fetchQuery

Execute a query from a Server Component:
Usage:

fetchMutation

Execute a mutation from a Server Component or Server Action:
Usage in a Server Action:

fetchAction

Execute an action from a Server Component or Server Action:
Usage:

Preloading for Client Components

preloadQuery

Preload query data in a Server Component to pass to a Client Component:
Server Component:
Client Component:

usePreloadedQuery

Use preloaded data in a Client Component and subscribe to updates:

Options

All functions accept a NextjsOptions object:
Parameters:
  • token - JWT authentication token
  • url - Convex deployment URL (defaults to process.env.NEXT_PUBLIC_CONVEX_URL)
  • skipConvexDeploymentUrlCheck - Skip URL validation for self-hosted backends
Example with authentication:

Route Handlers

Use Convex functions in Next.js API routes:

Client-side usage

For client-side reactivity, use the standard React hooks with ConvexProvider: Layout or root component:
Client Component:

Patterns

Server Component with Client Component

Combine server-side data fetching with client-side reactivity:

Server Actions

Authentication

Pass auth tokens from your auth provider:

Best practices

  • Use preloadQuery to hydrate Client Components with initial data
  • Execute mutations in Server Actions for progressive enhancement
  • Use fetchQuery for server-only pages that don’t need reactivity
  • Combine server and client rendering for optimal performance
  • Pass authentication tokens via the token option
  • Use environment variables for the Convex URL
  • Leverage Next.js caching strategies with fetchQuery

Type safety

All functions are fully type-safe with generated API types:

Caching

Next.js caches fetchQuery results by default. Control caching with Next.js options: