Next.js Quickstart
Learn how to query data from Convex in a Next.js app.
- Create a React app
Create a Next.js app using the
npx create-next-app
command.Choose
No
for TypeScript and the default option for every other prompt.npx create-next-app my-app
- Install the Convex client and server library
To get started, install the
convex
package 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
- Setup 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. Thedev
command 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.jsonl
file 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
tasks
table with the sample data into your Convex database with theimport
command.npx convex import tasks sampleData.jsonl
- Expose a database query
Add a new file
getTasks.js
in theconvex/
folder with a query function that loads the data.The default export declares an API function named after the file,
"getTasks"
.convex/getTasks.jsimport { query } from "./_generated/server";
export default query(async ({ db }) => {
return await db.query("tasks").collect();
}); - Connect the app to your backend
In
_app.js
, create aConvexReactClient
and pass it to aConvexProvider
wrapping your app.pages/_app.jsimport { 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} /> - Display the data in your app
In
index.js
, use theuseQuery
hook to fetch from your"getTasks"
API function.pages/index.jsimport { useQuery } from "./convex/_generated/react";
function Home() {
const tasks = useQuery("getTasks");
return (
<Head>…</Head>
<main className={styles.main}>
{JSON.stringify(tasks, null, 2)} - Start the app
Start the app, go to http://localhost:3000 in a browser, and see the serialized list of tasks at the top of the page.
npm run dev