Skip to main content

Using TakeShape with Next.js

  1. Create an API key for TakeShape:
  1. Create a .env file in your Next.js project's root (or open your file) and add your TakeShape API Key and API URL (found in the webapp's dashboard) to it.
.env
TAKESHAPE_API_KEY="YOUR KEY HERE"
TAKESHAPE_API_URL="YOUR ENDPOINT HERE"
  1. Create a new file called takeshape.client.js to configure your requests to TakeShape:
takeshape.client.js
export class Client {
constructor(apiUrl, apiKey) {
this.token = apiKey;
this.endpoint = apiUrl;
}
async graphql(params) {
const res = await fetch(this.endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.token}`
},
body: JSON.stringify(params)
});
return res;
}
}

export default new Client(process.env.TAKESHAPE_API_URL, process.env.TAKESHAPE_API_KEY);
  1. Finally, import the library and call it within the getStaticProps function of your page components:
pages/index.js
import Error from 'next/error';
import TakeShape from '../takeshape.client';

export async function getStaticProps() {
try {
const res = await TakeShape.graphql({query: ''});
return {
props: {
takeshapeWorks: res.ok
}
};
} catch (error) {
return {
props: {
error: error.message
}
};
}
}

export default function Page({takeshapeWorks, error}) {
if (error) {
return <Error statusCode={500} title={error} />;
}
return (
<div>
<h1>
Welcome to{' '}
<a href="https://app.takeshape.io/docs/get-started/ssg/nextjs/">Next.js{takeshapeWorks && ' and TakeShape!'}</a>
</h1>
</div>
);
}
note

Check out our takeshape-starter-nextjs repo for a basic integration of TakeShape with Next.js. Explore other starter projects to find other example Next.js and TakeShape projects, including one from the team behind Next.js