Using TakeShape with Next.js

1. Create an API key for TakeShape:

2. Create a .env file in your next.js project's root (or open your existing file) and add your TakeShape API Key and project ID (found in url) to it.

TAKESHAPE_API_KEY="YOUR KEY HERE"
TAKESHAPE_PROJECT="YOUR PROJECT ID HERE"


3. Using NPM or Yarn, install the dotenv, takeshape-routing, and isomorphic-fetch libraries:

Note: dotenv is not required if you've installed Next.js 9.4

npm install dotenv takeshape-routing isomorphic-fetch
# or
yarn add dotenv takeshape-routing isomorphic-fetch


4. Create a next.config.js file in your project root (or open your existing config file). Then update your Next project's configuration to provide the secrets from .env:

Note: if you're using Next.js 9.4, you can skip this step now that it supports .env loading by default!

require('dotenv').config()

exports.default = {
  env: {
  	TAKESHAPE_API_KEY: process.env.TAKESHAPE_API_KEY,
  	TAKESHAPE_PROJECT: process.env.TAKESHAPE_PROJECT
  },
}


5. Create a new file called takeshape.client.js to configure your requests to TakeShape:

import fetch from 'isomorphic-fetch'
import { getImageUrl } from 'takeshape-routing'

export const TAKESHAPE_PROJECT = process.env.TAKESHAPE_PROJECT

export class Client {
	constructor(projectId, apiKey) {
		this.token = apiKey
		this.endpoint = `https://api.takeshape.io/project/${projectId}/graphql`
	}
	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
	}
	getImageUrl
}

export default new Client(TAKESHAPE_PROJECT, process.env.TAKESHAPE_API_KEY)

6. Finally, import the library and call it within the getStaticProps function of your page components:

import TakeShape from '../takeshape.client'

const HelloWorld = ({takeshapeWorks}) => (
	<h1>
		Hello Next.js {takeshapeWorks && <span>&amp; TakeShape!</span>}
	</h1>
)

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

export default HelloWorld

Join us

Interested in joining the team as coworker or investor?

contact@takeshape.com