Our Community has also created many great video tutorials you can follow:
First, create a new Next.js application using create-next-app, which sets up everything automatically for you.
To create a project, run the following command and follow the wizard:
npx create-next-app@latest
Then enter the project directory and start the development server:
cd my-appnpm run dev
When it comes to fetching data, Next recommends the following:
perform the fetch on the Server, to reduce the back-and-forth communication between client and server;
use Next.js fetch
API, and call it whenever you need it, be it a layout, a page or a specific component.
Let's start by installing @datocms/cda-client
, a lightweight, TypeScript-ready package that offers various helpers around the native Fetch API to perform GraphQL requests towards DatoCMS Content Delivery API:
npm install --save @datocms/cda-client
We can now create a function we can use in all of our components that need to fetch content from DatoCMS: Create a new directory called lib
, and inside of it, add a file called datocms.js
:
// lib/datocms.jsimport { executeQuery } from '@datocms/cda-client';export const performRequest = (query, options) => {return executeQuery(query, {...options,token: process.env.NEXT_DATOCMS_API_TOKEN,environment: process.env.NEXT_DATOCMS_ENVIRONMENT,});}
While the above function works for simple cases, we strongly suggest to take a look at the next section, where we cover more details about data fetching, and introduce a more flexible and optimized performRequest()
.
You can see that to build the right authentication header, we're using an environment variable prefixed by NEXT_
. To create the API token for a DatoCMS project, go in the "Settings > API Tokens" section, making sure you only give it permission to access the Content Delivery API and the Content Delivery API with draft content:
Next, go to app/page.js
— that is, the component that renders the homepage of our project — define the GraphQL query to be executed, and in the component use the performRequest()
function to perform the request:
import { performRequest } from 'lib/datocms';const PAGE_CONTENT_QUERY = `query Home {homepage {titledescription {value}}}`;export default async function Home() {const { homepage } = await performRequest(PAGE_CONTENT_QUERY);// [...]}
The PAGE_CONTENT_QUERY
is the GraphQL query, and of course, it depends on the models available in your specific DatoCMS project.
You can learn everything you need regarding how to build GraphQL queries on our Content Delivery API documentation.