Since Next 9.3, the way you fetch content from external sources is by exporting one of the following async functions from your page components:
getServerSideProps
to fetch data on each request;
getStaticProps
to fetch data at build time.
// pages/index.jsexport async function getStaticProps(context) {return {props: {}, // will be passed to the page component as props}}export default Homepage(props) {
Inside these functions, we can use any Node.JS GraphQL client (or HTTP client, really) to fetch content from DatoCMS and pass it down to your component.
We suggest using lightweight libraries like graphql-request
or unfetch
since they're all you need to get the job done.
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:
npm init next-app
Then enter inside the project directory, install the graphql-request
package, and start the development server:
cd my-appyarn add graphql-requestyarn dev
First you'll need to setup a GraphQL client pointing to one of our GraphQL Content Delivery API endpoints. Create a new directory lib
, and inside of it create a file called datocms.js
:
import { GraphQLClient } from "graphql-request";export function request({ query, variables, preview }) {const endpoint = preview? `https://graphql.datocms.com/preview`: `https://graphql.datocms.com/`;const client = new GraphQLClient(endpoint, {headers: {authorization: `Bearer ${process.env.NEXT_DATOCMS_API_TOKEN}`}});return client.request(query, variables);}
On line 10 we're using an environment variable starting with NEXT_
so that it will be embedded into the bundle.
To create the API token for a DatoCMS project, go in the "Settings > API Tokens" section, making sure you only give it permissions to access the (read-only) Content Delivery API.
Next, go to pages/index.js
— that is, the component that renders the homepage of our project — and define the getStaticProps
function:
import { request } from "../lib/datocms";const HOMEPAGE_QUERY = `query HomePage($limit: IntType) {allBlogPosts(first: $limit) {title}}`;export async function getStaticProps() {const data = await request({query: HOMEPAGE_QUERY,variables: { limit: 10 }});return {props: { data }};}export default function Home({ data }) {return <div>{JSON.stringify(data, null, 2)}</div>;}
The HOMEPAGE_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.
For more information on what to do next, we recommend reading the next sections of this integration guide!