Skip to main content

Next.js

Next.js is a React web development framework. When used with Convex, Next.js provides:

  • File-system based routing
  • Fast refresh in development
  • Font and image optimization

and more!

This pages covers the App Router variant of Next.js. Alternatively see the Pages Router version of this page.

Getting started

Follow the Next.js Quickstart to add Convex to a new or existing Next.js project.

Adding authentication

Client-side only

The simplest way to add user authentication to your Next.js app is to follow our React-based authentication guides for Clerk or Auth0, inside your app/ConvexClientProvider.tsx file. For example this is what the file would look like for Auth0:

app/ConvexClientProvider.tsx
"use client";

import { Auth0Provider } from "@auth0/auth0-react";
import { ConvexReactClient } from "convex/react";
import { ConvexProviderWithAuth0 } from "convex/react-auth0";
import { ReactNode } from "react";

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

export function ConvexClientProvider({ children }: { children: ReactNode }) {
return (
<Auth0Provider
domain={process.env.NEXT_PUBLIC_AUTH0_DOMAIN!}
clientId={process.env.NEXT_PUBLIC_AUTH0_CLIENT_ID!}
authorizationParams={{
redirect_uri:
typeof window === "undefined" ? undefined : window.location.origin,
}}
useRefreshTokens={true}
cacheLocation="localstorage"
>
<ConvexProviderWithAuth0 client={convex}>
{children}
</ConvexProviderWithAuth0>
</Auth0Provider>
);
}

Custom loading and logged out views can be built with the helper Authenticated, Unauthenticated and AuthLoading components from convex/react, see the Convex Next.js demo for an example.

If only some routes of your app require login, the same helpers can be used directly in page components that do require login instead of being shared between all pages from app/ConvexClientProvider.tsx. Share a single ConvexReactClient instance between pages to avoid needing to reconnect to Convex on client-side page navigation.

Server and client side

If you also want to access user information or load Convex data requiring ctx.auth from Server Components, Server Actions or Route Handlers, you need to use the Next.js specific SDKs provided by Clerk and Auth0.

Follow the respective quickstart:

Additional .env.local configuration is needed for these hybrid SDKs.

Server rendering (SSR)

Next.js automatically renders both Client and Server Components on the server during the initial page load.

To keep your UI automatically reactive to changes in your Convex database it needs to use Client Components. The ConvexReactClient will maintain a connection to your deployment and will get updates as data changes and that must happen on the client.

See the dedicated Server Rendering page for more details about preloading data for Client Components, fetching data and authentication in Server Components, and implementing Route Handlers.