Next.js Pages Quickstart
Learn how to query data from Convex in a Next.js app using the Pages Router.
Alternatively see the App Router version of this quickstart.
- Create a React app
Create a Next.js app using the
npx create-next-appcommand.Choose the default option for every prompt (hit Enter).
npx create-next-app@latest my-app --no-app --js - Install the Convex client and server library
To get started, install the
convexpackage which provides a convenient interface for working with Convex from a React app.Navigate to your app and install
convex.cd my-app && npm install convex - Set up a Convex dev deployment
Next, run
npx convex dev. This will prompt you to log in with GitHub, create a project, and save your production and deployment URLs.It will also create a
convex/folder for you to write your backend API functions in. Thedevcommand will then continue running to sync your functions with your dev deployment in the cloud.npx convex dev - Create sample data for your database
In a new terminal window, create a
sampleData.jsonlfile with some sample data.sampleData.jsonl{"text": "Buy groceries", "isCompleted": true}
{"text": "Go for a swim", "isCompleted": true}
{"text": "Integrate Convex", "isCompleted": false} - Add the sample data to your database
Now that your project is ready, add a
taskstable with the sample data into your Convex database with theimportcommand.npx convex import --table tasks sampleData.jsonl - Expose a database query
Add a new file
tasks.jsin theconvex/folder with a query function that loads the data.Exporting a query function from this file declares an API function named after the file and the export name,
api.tasks.get.convex/tasks.jsimport { query } from "./_generated/server";
export const get = query({
args: {},
handler: async (ctx) => {
return await ctx.db.query("tasks").collect();
},
}); - Connect the app to your backend
In
pages/_app.js, create aConvexReactClientand pass it to aConvexProviderwrapping your app.pages/_app.jsimport "@/styles/globals.css";
import { ConvexProvider, ConvexReactClient } from "convex/react";
const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL);
export default function App({ Component, pageProps }) {
return (
<ConvexProvider client={convex}>
<Component {...pageProps} />
</ConvexProvider>
);
} - Display the data in your app
In
pages/index.js, use theuseQueryhook to fetch from yourapi.tasks.getAPI function.pages/index.jsimport { useQuery } from "convex/react";
import { api } from "../convex/_generated/api";
export default function Home() {
const tasks = useQuery(api.tasks.get);
return (
<main className="flex min-h-screen flex-col items-center p-24">
{tasks?.map(({ _id, text }) => (
<div key={_id}>{text}</div>
))}
</main>
);
} - Start the app
Start the app, open http://localhost:3000 in a browser, and see the list of tasks.
npm run dev