In this tutorial, we will learn how to use Strapi, ChatGPT, and Next.js to build an app that displays recipes using AI.
This tutorial aims to show how to combine these different technologies and how integrating AI can enrich the user experience of our apps.
For example, in a recipe-sharing app, a content management system such as Strapi would be in charge of structured storage and management of the data about each recipe. By integrating AI, we can elevate the functionality with additional insights, suggestions, or personalisation according to the particular user.
To follow this tutorial, we will need the following:
Strapi or Strapi CMS is an open-source headless content management system that allows us to create APIs quickly. The headless architecture separates the content management and content delivery layers. This feature will enable us to consume the content via API and use whatever frontend technology (React.Js, Vue, etc.). Strapi CMS also provides plugins or Strapi plugins that can extend the functionality and add custom features to the CMS. The role of Strapi in this project will be to serve as the backend, which is responsible for storing and serving recipes to the frontend. So, without further ado, let's dive into the code.
Let's create a folder that will contain the source code for our Strapi API. First, we open a terminal and navigate to any directory of our choice, and run the commands below:
mkdir strapi-tutorial
cd strapi-tutorial
This folder will contain both our frontend and backend codes. Now, let's create our Strapi API with the command below:
npx create-strapi-app@latest strapi-recipe-api
Once this is complete and it finishes installing the dependencies, we should receive a confirmation like the one below!
It should automatically direct us to the Strapi dashboard as it starts our project. We can create our administrator here, so we must fill out the form and click the Let's start button.
We should now see the dashboard which looks like this:
We want to create the Collection type, which would be the recipe and its various keys and values, such as ingredients and instructions.
Click Content-Type Builder from the left side panel, and then on the left, under Collection Types, we should see Create new collection type. Click on that and type Recipe into the display name.
Click continue, and from here, click text as the data type like this:
Then enter title
field and make sure short text is selected.
Now we need to add the rest of the fields, so click on Add another field, add text, and enter description
, but this time select the long text. The rest of the fields to add are like so:
ingredients
- long textinstructions
- long textAfter adding instructions
, we click Finish. We should now see our newly created Collection type: Recipe and its different fields. Click save at the top right. This action will restart the server. Once done, we can play around with our collection and add some recipes.
From the left side panel, now select Content Manager under Collection Types, select Recipe, and then select create new entry on the top right.
We can ask ChatGPT to generate the inputs for us with the following prompt: "Give me a recipe idea with a title, description, ingredients, and instructions" and fill in the various fields below:
Now go ahead and click save in the top right. This action should prompt a success message, and now, if we click Recipe on the left, we should see our latest recipe entry in the table.
Tick the entry, and then select Publish:
By default, Strapi requires authentication to query our API and receive information, but that is outside the scope of this tutorial. Instead, we will make our API publicly accessible. We can find more about authentication and REST API in this blog post.
From the left sidebar, click on Settings. Again, on the left panel under USERS & PERMISSIONS PLUGIN, click on Roles, then click on Public from the table on the right. Now scroll down, click on Recipe, and tick Select all to allow the user to access information without authentication.
Now if we copy and paste the following into our browser we should be able to fetch the data from our API.
http://localhost:1337/api/recipes
So far we've learned what Strapi is and what it does, we've got the API up and running and added some data, now let's see how we can integrate ChatGPT in our project.
First navigate to the terminal and run the below command in the root directory:
yarn strapi generate
This will begin the process of generating our own custom API. Choose the API option, give it the name recipe-gpt
, and select "no" when it asks us if this is for a plugin.
Inside the src
directory, If we check the api
directory in our code editor, we should see the newly created APIs for recipe
and recipe-gpt
with their routes, controllers, and services.
Let's check it works by uncommenting the code in each file, restarting the project in the terminal, and navigating to the admin dashboard. Now, once again, click Settings > Soles > Public, then scroll down to Select all on the recipe-gpt
API to make the permissions public, and click save in the top right.
Now if we enter the following into our browser and click enter, we should get an "ok" message.
http://localhost:1337/api/recipe-gpt
Okay, now we've confirmed the API endpoint is working, let's connect it to OpenAI first, install the OpenAI package, navigate to the route directory, and run the command below in our terminal
yarn add openai
Then in the .env
file add the following environment variable:
OPENAI=< OpenAI api key here>
Now under the recipe-gpt
directory change the code in the routes directory to the following:
1module.exports = {
2 routes: [
3 {
4 method: "POST",
5 path: "/recipe-gpt/exampleAction",
6 handler: "recipe-gpt.exampleAction",
7 config: {
8 policies: [],
9 middlewares: [],
10 },
11 },
12 ],
13};
Change the code in the controller
directory to the following:
1"use strict";
2
3module.exports = {
4 exampleAction: async (ctx) => {
5 try {
6 const response = await strapi
7 .service("api::recipe-gpt.recipe-gpt")
8 .recipeService(ctx);
9
10 ctx.body = { data: response };
11 } catch (err) {
12 console.log(err.message);
13 throw new Error(err.message);
14 }
15 },
16};
And the code in the services
directory to the following:
1"use strict";
2const { OpenAI } = require("openai");
3const openai = new OpenAI({
4 apiKey: process.env.OPENAI,
5});
6
7/**
8 * recipe-gpt service
9 */
10
11module.exports = ({ strapi }) => ({
12 recipeService: async (ctx) => {
13 try {
14 const input = ctx.request.body.data?.input;
15 const completion = await openai.chat.completions.create({
16 messages: [{ role: "user", content: input }],
17 model: "gpt-3.5-turbo",
18 });
19
20 const answer = completion.choices[0].message.content;
21
22 return {
23 message: answer,
24 };
25 } catch (err) {
26 ctx.body = err;
27 }
28 },
29});
Now we can make a post request which contains input (which will be from our frontend) and return answers from ChatGPT.
We can check the connection to our post route by pasting the below code in our terminal:
1curl -X POST \
2 http://localhost:1337/api/recipe-gpt/exampleAction \
3 -H 'Content-Type: application/json' \
4 -d '{
5 "data": {
6 "input": "Give me some interesting nutritional information"
7 }
8}'
So we now have the API set up to deliver content (recipes) and a custom API set up to provide information from ChatGPT on any input we might send to it from the frontend. Let's move on to the next part (whoops, no pun intended).
Next.js is a React framework that simplifies the development of complex and high-performance web applications. It offers many built-in features, such as server-side rendering, automatic code splitting, automatic image optimization, and API routes. Next.Js streamlines the development process and ensures fast and responsive user experiences.
Let's create our frontend directory. Navigate to the main folder, strapi-tutorial
, and enter the following command in our terminal.
npx create-next-app recipe-frontend
Navigate into this newly created directory and run the below :
yarn dev
This should start and run the project in http://localhost:3000
, when accessed through the web browser, we should be able to see the image below:
Open up the project in our code editor and look under the pages
directory and click the index.js
file. This file is the entry point to the application and where the code for this welcome page exists. Delete everything and paste the code below into this file.
1import Head from 'next/head';
2import styles from '../styles/Home.module.css';
3
4export default function Home() {
5 return (
6 <div className={styles.container}>
7 <Head>
8 <title>Create Next App</title>
9 <meta name="description" content="Generated by create next app" />
10 <link rel="icon" href="/favicon.ico" />
11 </Head>
12
13 <main className={styles.main}>
14 <h1 className={styles.title}>
15 Welcome to <a href="https://nextjs.org">Strapi Recipe!</a>
16 </h1>
17 </main>
18
19 <footer className={styles.footer}>
20 <a
21 href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
22 target="_blank"
23 rel="noopener noreferrer"
24 >
25 Powered by Strapi
26 </a>
27 </footer>
28 </div>
29 );
30}
Save the file. We should notice the difference in our web browser as the code automatically reloads.
Next, we will want to create some re-usable components to display the recipes for our users. To speed things up, let's use a component library. Navigate to the terminal, and run the command below:
yarn add antd
First, let's add a card component. Create a directory components
outside of the pages
directory and then create a file called RecipeCard.jsx
. Paste the following code inside the new file:
1import { Card } from 'antd';
2import Image from 'next/image';
3
4export default function RecipeCard({ title, bordered, content }) {
5 return (
6 <div style={{ cursor: 'pointer', width: '400px' }}>
7 <Card
8 title={title}
9 bordered={bordered}
10 cover={
11 <Image
12 alt="example"
13 unoptimized
14 width={400}
15 height={200}
16 src={'https://placehold.co/400x200'}
17 />
18 }
19 >
20 {content.length > 200 ? content.slice(0, 200) + '...' : content}
21 </Card>
22 </div>
23 );
24}
By default Next.Js reccomends us to use the images.domains
to be able to load external images with next/image
, so just add the following to our next.config.js
file.
1/** @type {import('next').NextConfig} */
2const nextConfig = {
3 reactStrictMode: true,
4 swcMinify: true,
5 images: {
6 domains: ['placehold.co'],
7 },
8};
9
10module.exports = nextConfig;
Let's create a way to view the details of our recipes using a modal from the component library, create a file in components
directory called RecipeModal.jsx
and paste in the code below:
1import { Modal } from 'antd';
2
3export default function RecipeModal({
4 title,
5 open,
6 setOpen,
7 width = 1000,
8 description,
9 ingredients,
10 instructions,
11}) {
12 return (
13 <div>
14 <Modal
15 title={title}
16 centered
17 open={open}
18 onOk={() => setOpen(false)}
19 onCancel={() => setOpen(false)}
20 width={width}
21 >
22 <h3>Description</h3>
23 <p>{description}</p>
24 <h3>Ingredients</h3>
25 <p>{ingredients}</p>
26 <h3>Instructions</h3>
27 <p>{instructions}</p>
28 </Modal>
29 </div>
30 );
31}
Now, we have our components for displaying the recipes we can move on to fetching our content from Strapi and working out the logic to connect the data and the UI together.
So, now that we have Strapi ready with our API and we've set up the frontend Next.Js app and built some components to host our data, we're finally ready to make the connection. We will want to create some reusable piece of logic that encapsulates the fetching of our data and the storing in state; this is a perfect use for a custom hook.
First, let's create the fetch function for our API, so create a utils
folder in the root directory. Inside this new folder, create a file called api.js
, and paste the below code there.
1const baseUrl = 'http://localhost:1337';
2
3export async function fetchRecipes() {
4 try {
5 const res = await fetch(`${baseUrl}/api/recipes`);
6 return await res.json();
7 } catch (e) {
8 console.error('Error fetching data:', error);
9 throw error;
10 }
11}
In the root directory create a hooks
folder, and inside that, create a file named useGetRecipe.js
and add the following code:
1import { useEffect, useState } from 'react';
2import { fetchRecipes } from '../utils/api';
3
4export function useGetRecipe() {
5 const [recipes, setRecipes] = useState(null);
6 const [loading, setLoading] = useState(true);
7 const [error, setError] = useState(null);
8
9 useEffect(() => {
10 async function fetchData() {
11 try {
12 const { data } = await fetchRecipes();
13 console.log('data - ', data);
14 setRecipes(data);
15 } catch (e) {
16 setError(e);
17 } finally {
18 setLoading(false);
19 }
20 }
21
22 fetchData();
23 }, []);
24
25 return { recipes, loading, error };
26}
This hook encapsulates all of the logic to call our API, set the loading state while we wait for data, set the data in the state, and save any errors we might get. We can easily re-use this hook without re-writing this logic anywhere else.
Import it into index.js
and use it to display our RecipeCard
component. The index.js
file should now look like the code below:
1import Head from 'next/head';
2import styles from '../styles/Home.module.css';
3import { useGetRecipe } from '../hooks/useGetRecipe';
4import dynamic from 'next/dynamic';
5const RecipeCard = dynamic(() => import('../components/RecipeCard'), {
6 ssr: false,
7});
8
9export default function Home() {
10 const { recipes, loading, error } = useGetRecipe();
11
12 return (
13 <div className={styles.container}>
14 <Head>
15 <title>Create Next App</title>
16 <meta name="description" content="Generated by create next app" />
17 <link rel="icon" href="/favicon.ico" />
18 </Head>
19
20 <main className={styles.main}>
21 <div>
22 <h1 className={styles.title}>
23 Welcome to <a href="https://nextjs.org">Strapi Recipe!</a>
24 </h1>
25 </div>
26 <div className={styles.recipeContainer}>
27 {!loading && recipes ? (
28 recipes.map((recipe, i) => {
29 const { title, description } = recipe.attributes;
30 return (
31 <RecipeCard
32 key={i}
33 title={title}
34 bordered={true}
35 content={description}
36 />
37 );
38 })
39 ) : (
40 <p>...Loading</p>
41 )}
42 </div>
43 </main>
44
45 <footer className={styles.footer}>
46 <a
47 href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
48 target="_blank"
49 rel="noopener noreferrer"
50 >
51 Powered by Strapi
52 </a>
53 </footer>
54 </div>
55 );
56}
Add the following styles to the Home.module.css
file that is inside the styles
directory:
1.recipeContainer {
2 margin-top: 50px;
3 display: flex;
4 flex-wrap: wrap;
5}
6
7.item {
8 margin: 5px;
9}
Now, if we reload the project and navigate to localhost
we should be able to see the recipe we added as shown below:
Now let's try and use the modal so we can click on the recipe and view more details about it.
We will just need to import our RecipeModal
component, add a handleClick
method and save our recipe in state. The index.js
component should now look as below:
1import { useState } from 'react';
2import Head from 'next/head';
3import styles from '../styles/Home.module.css';
4import { useGetRecipe } from '../hooks/useGetRecipe';
5import dynamic from 'next/dynamic';
6const RecipeCard = dynamic(() => import('../components/RecipeCard'), {
7 ssr: false,
8});
9const RecipeModal = dynamic(() => import('../components/RecipeModal'), {
10 ssr: false,
11});
12
13export default function Home() {
14 const { recipes, loading, error } = useGetRecipe();
15 const [recipe, setRecipe] = useState(null);
16 const [open, setOpen] = useState(false);
17
18 const handleCardClick = (recipeToView) => {
19 setRecipe(recipeToView);
20 setOpen(true);
21 };
22
23 return (
24 <div className={styles.container}>
25 <Head>
26 <title>Create Next App</title>
27 <meta name="description" content="Generated by create next app" />
28 <link rel="icon" href="/favicon.ico" />
29 </Head>
30
31 <main className={styles.main}>
32 <div>
33 <h1 className={styles.title}>
34 Welcome to <a href="https://nextjs.org">Strapi Recipe!</a>
35 </h1>
36 </div>
37 <div className={styles.recipeContainer}>
38 {!loading && recipes ? (
39 recipes.map((recipe, i) => {
40 const { title, description } = recipe.attributes;
41 return (
42 <div
43 onClick={() => handleCardClick(recipe.attributes)}
44 key={i}
45 className={styles.item}
46 >
47 <RecipeCard
48 title={title}
49 bordered={true}
50 content={description}
51 />
52 </div>
53 );
54 })
55 ) : (
56 <p>...Loading</p>
57 )}
58 </div>
59 <RecipeModal
60 title={recipe?.title}
61 open={open}
62 setOpen={setOpen}
63 description={recipe?.description}
64 ingredients={recipe?.ingredients}
65 instructions={recipe?.instructions}
66 />
67 </main>
68
69 <footer className={styles.footer}>
70 <a
71 href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
72 target="_blank"
73 rel="noopener noreferrer"
74 >
75 Powered by Strapi
76 </a>
77 </footer>
78 </div>
79 );
80}
Now if we navigate to localhost
and click on a recipe we should be able to see all of it's details.
We have connected our data from Strapi with our frontend components and everything seems to be working smoothly, feel free to add more recipes from the Strapi dashboard and watch them appear in the frontend. Next up, let's use our API connected to ChatGPT to enhance the functionality of our app.
Let's enhance the functionality by adding an extra button to our modal allowing users to make the dish plant-based. We can do this by sending the ingredients of the recipe to our ChatGPT API, which will then provide us with suggestions to change them to plant-based alternatives.
First things first, let's set up the API call with fetch
in the utils
directory. Add the code below to api.js
.
1export async function fetchRecipeGPTData(ingredients) {
2 try {
3 const response = await fetch(`${baseUrl}/api/recipe-gpt/exampleAction`, {
4 method: 'POST',
5 headers: {
6 'Content-Type': 'application/json',
7 },
8 body: JSON.stringify({
9 data: {
10 input: `Here are the ingredients for a recipe ${ingredients}, provide me with a plant based version`,
11 },
12 }),
13 });
14
15 return await response.json();
16 } catch (e) {
17 console.error('Error fetching data:', error);
18 throw error;
19 }
20}
As we can see, we are just passing the ingredients in with a simple prompt to GPT.
Next under the hooks
directory create a file named useRecipeGPTData.js
and add the code below:
1import { useState } from 'react';
2import { fetchRecipeGPTData } from '../utils/api';
3
4export function useRecipeGPTData() {
5 const [data, setData] = useState();
6 const [isLoading, setIsLoading] = useState(false);
7 const [error, setError] = useState();
8
9 const fetchData = async (ingredients) => {
10 setIsLoading(true);
11 try {
12 const res = await fetchRecipeGPTData(ingredients);
13 const dataToSave = res.data.message;
14
15 setData(dataToSave);
16 } catch (e) {
17 setError(e);
18 } finally {
19 setIsLoading(false);
20 }
21 };
22 return { data, fetchData, isLoading, setData, error };
23}
Now we can use this hook to prompt GPT from anywhere in our app.
All that's left to do is to connect this function to our modal so we can allow users to query it.
In index.js
, import useRecipeGPTData
and pass some of the functions in to the RecipeModal
. The index.js
file should now look like this :
1import { useState } from 'react';
2import Head from 'next/head';
3import styles from '../styles/Home.module.css';
4import { useGetRecipe } from '../hooks/useGetRecipe';
5import { useRecipeGPTData } from '../hooks/useRecipeGPTData';
6import dynamic from 'next/dynamic';
7const RecipeCard = dynamic(() => import('../components/RecipeCard'), {
8 ssr: false,
9});
10const RecipeModal = dynamic(() => import('../components/RecipeModal'), {
11 ssr: false,
12});
13
14export default function Home() {
15 const { recipes, loading, error } = useGetRecipe();
16 const { data, fetchData, isLoading, setData } = useRecipeGPTData();
17 const [recipe, setRecipe] = useState(null);
18 const [open, setOpen] = useState(false);
19
20 const handleCardClick = (recipeToView) => {
21 setRecipe(recipeToView);
22 setOpen(true);
23 };
24
25 const handleCloseModal = () => {
26 setData('');
27 setOpen(false);
28 };
29
30 return (
31 <div className={styles.container}>
32 <Head>
33 <title>Create Next App</title>
34 <meta name="description" content="Generated by create next app" />
35 <link rel="icon" href="/favicon.ico" />
36 </Head>
37
38 <main className={styles.main}>
39 <div>
40 <h1 className={styles.title}>
41 Welcome to <a href="https://nextjs.org">Strapi Recipe!</a>
42 </h1>
43 </div>
44 <div className={styles.recipeContainer}>
45 {!loading && recipes ? (
46 recipes.map((recipe, i) => {
47 const { title, description } = recipe.attributes;
48 return (
49 <div
50 onClick={() => handleCardClick(recipe.attributes)}
51 key={i}
52 className={styles.item}
53 >
54 <RecipeCard
55 title={title}
56 bordered={true}
57 content={description}
58 />
59 </div>
60 );
61 })
62 ) : (
63 <p>...Loading</p>
64 )}
65 </div>
66 <RecipeModal
67 title={recipe?.title}
68 open={open}
69 handleCloseModal={handleCloseModal}
70 description={recipe?.description}
71 ingredients={recipe?.ingredients}
72 instructions={recipe?.instructions}
73 getRecipeGPTData={fetchData}
74 recipeGPTData={data}
75 isLoading={isLoading}
76 />
77 </main>
78
79 <footer className={styles.footer}>
80 <a
81 href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
82 target="_blank"
83 rel="noopener noreferrer"
84 >
85 Powered by Strapi
86 </a>
87 </footer>
88 </div>
89 );
90}
Lastly, change the code in RecipeModal
to display a button to query the API and a section for the plant-based version of the dish. The RecipeModal
should now look like the one below:
1import { Modal } from 'antd';
2
3export default function RecipeModal({
4 title,
5 open,
6 handleCloseModal,
7 width = 1000,
8 description,
9 ingredients,
10 instructions,
11 getRecipeGPTData,
12 recipeGPTData,
13 isLoading,
14}) {
15 return (
16 <div>
17 <Modal
18 title={title}
19 centered
20 open={open}
21 onOk={handleCloseModal}
22 onCancel={handleCloseModal}
23 width={width}
24 >
25 <h3>Description</h3>
26 <p>{description}</p>
27 <h3>Ingredients</h3>
28 <p>{ingredients}</p>
29 {!isLoading ? (
30 <button onClick={() => getRecipeGPTData(ingredients)}>
31 Make plant based
32 </button>
33 ) : (
34 <p>Loading...</p>
35 )}
36
37 <h3>Instructions</h3>
38 <p>{instructions}</p>
39 {recipeGPTData ? (
40 <div>
41 <h3>Plant based version</h3>
42 <p>{recipeGPTData}</p>
43 </div>
44 ) : null}
45 </Modal>
46 </div>
47 );
48}
We should now be able to press the newly added button to generate a plant based version of the dish with our GPT powered API.
So now we have seen how to set up a Strapi API to serve content to our frontend (in our case, Next.js, a React.Js framework). We have also shown how to set up custom API endpoints and connect them to other technologies, such as ChatGPT. This can be used to make our apps appealing to a wider audience by customizing the functionality.
Hopefully, this has inspired us to explore this area further and think of new ways to improve our apps.
Hey! 👋 I'm Mike, a seasoned web developer with 5 years of full-stack expertise. Passionate about tech's impact on the world, I'm on a journey to blend code with compelling stories. Let's explore the tech landscape together! 🚀✍️