Now that you have embedded your app in the BigCommerce platform, you’re ready to integrate the BigCommerce API.
Anytime you make an API call to BigCommerce, you need to pass in the access token. Storing the access token in a database allows you to persist the session when you call /auth, /load, or /uninstall endpoints.
This step demonstrates how to integrate the sample app with Cloud Firestore, a cloud-hosted NoSQLFirebase database, and MySQL, a relational database management system.
If using Firebase, install firebase, jsonwebtoken, and swr npm packages.
If using MySQL, install mysql2, jsonwebtoken, and swr npm packages.
These instructions have been tested using the firebase v9 package. You can view a list of all the tested package versions in the package.json file on the Step 3 branch of this sample app’s repo.
Open package.json in your text editor.
Update the scripts property to include the db:setup script.
In the root directory of your project, add a types folder.
In the types folder, create auth.ts, db.ts, and index.ts files.
Open the auth.ts file and export User, SessionProps, and QueryParams TypeScript type definitions. You can view auth.ts (GitHub).
db.ts file. Import SessionProps from ./index and export StoreData, UserData, and Db TypeScript type definitions. You can view db.ts (GitHub).index.ts file and export all interfaces. You can view index.ts (GitHub).If ngrok stops working or your ngrok session expires, restart the tunnel to get the new {ngrok_url} and update the callback URLs in the Developer Portal and the AUTH_CALLBACK in the .env file.
React’s Context API is a state management tool that streamlines the process of passing data to multiple components at different nesting levels. It lets you pass data through the component tree without having to pass props through multiple levels of React components. To learn more about Context, see React’s Context guide.
In the root of your app, create a context folder.
In the context folder, create a session.tsx file.
Add the logic to create a context. You can view session.tsx (GitHub).
You use a JSON Web Token (JWT) to securely transmit information encoded as a JSON object between parties. To learn more about JWT, see the Internet Engineering Task Force documentation.
Open the .env file.
Enter a JWT secret. Your JWT key should be at least 32 random characters (256 bits) for HS256.
The JWT key should be at least 32 random characters (256 bits) for HS256.
In the lib folder, open the auth.ts file.
At the top of the file, add the following imports:
.env:process.env global variable from the BigCommerce instances.QueryParams interface.bigcommerceSigned variable, export the bigcommerceClient function.getBCAuth and getBCVerify functions.setSession, getSession, and removeDataStore functions.encodePayload and decodePayload functions. You can view auth.ts (GitHub)In this section of the tutorial, we provide config and initialization code for both Firebase and MySQL databases. Depending on the database you choose to integrate your app with, use the configuration instructions specific to your setup.
For Firebase configuration instructions, see Set up Firebase database.
For MySQL configuration instructions, see Set up MySQL database.
Cloud Firestore is a cloud-hosted NoSQL Firebase database built on Google’s infrastructure. To learn more about Firebase, including how-to guides and code samples, see Firebase Documentation. For a quickstart on how to set up your Cloud Firestore, see Get started.
Sign in to Cloud Firestore using your Google account. To create a Google account, visit the Google signup page.
Once logged in, click Go to console in the top right corner.
In the Firebase console, click Add project.
Enter your project name and click Continue.
Click Create project.
In your Firebase project console, click on the settings icon that resembles a gear in the top left corner.
Select Project settings from the dropdown menu.
Under the General tab, scroll down to Your apps and click on the code icon (</>) to select the web platform.
Type in the name of your app and click Register app.
Make a note of the Firebase apiKey, authDomain, and projectId. You will need that information to update the app’s environment variables.
In your Firebase console, click Firestore Database under Build in the left pane. Follow the steps to create a Cloud Firestore database.
Click Create database.
Choose Start in test mode.
Select your Cloud Firestore location and click Enable.
.env file, specify the database type.In the development mode, every time you modify your environment variables, make sure to restart the development server to capture the changes, using npm run dev.
In the lib folder, create a dbs folder.
In the dbs folder, create a firebase.ts file.
At the top of the file, import the Firebase packages and TypeScript definitions. You can view firebase.ts (GitHub).
firebase.initializeApp() will initialize the app. For initialized apps, call firebase.app() to retrieve the Firebase app instance.MySQL is a relational database management system. For instructions on how to set up and use MySQL, see Getting Started with MySQL. Once you complete the database setup, make a note of the MySQL host, domain, username, password, and port variables. You will need them to update the app’s environment variables in the next step.
.env file, specify the database type.In the development mode, every time you modify your environment variables, make sure to restart the development server to capture the changes, using npm run dev.
In the dbs folder, create a mysql.ts file.
At the top of the file, add the following imports:
In the lib folder, create a db.ts file.
Open the db.ts file and add the following imports at the top of the file.
If you’re using MySQL, set up the initial tables by navigating to the root directory of your project and running the following script:
Open the auth.ts file nested inside the pages/api folder.
encodePayload, getBCVerify, and setSession from /lib/auth. Your imports should now look like this:Open the load.ts file nested inside the pages/api folder.
Import encodePayload, getBCVerify, and setSession from /lib/auth. Your imports should now look like this:
Open the uninstall.ts file nested inside the pages/api folder.
Import getBCVerify and removeSession from /lib/auth. Your imports should now look like this:
The Products endpoint retrieves your products summary from the Catalog API.
In the pages/api folder, create a new folder called products.
In the products folder, create an index.ts file. This will create a /products route.
At the top of the file, import the following packages:
products function, which awaits the data returned from bigcommerce.get. You can view index.ts (GitHub). The products function calls the getSession function to retrieve the session’s access token and store hash.To consume the Products endpoint, create a custom React hook using SWR.
In the lib folder, create a hooks.ts file.
At the top of the file, import the useSWR React hook from SWR and useSession from Context.
fetcher function.The fetcher function accepts the API URL and returns data asynchronously.
useProducts function. You can view hooks.ts (GitHub).useSWR accepts two arguments: the API URL and the fetcher function. The fetcher function takes the /api/products URL passed in from the useProduct function. The useProducts function destructures the data returned by the useSWR hook.
In the app’s root directory, create a components folder.
In the components folder, create a header.tsx file.
Import Box and Link components from BigDesign.
Header functional component. You can view header.tsx (GitHub).In the pages folder, open the index.tsx file.
At the top of the file, replace the existing import with the following:
Index functional component. You can view index.tsx (GitHub).summary creates the Flex component with three Box components inside of it. inventory_count, variant_count, and primary_category_name are populated with data returned from calling the /catalog/summary endpoint added in Add the Products endpoint.
For the complete list of properties returned by the /catalog/summary endpoint, see Get a Catalog Summary.
In the root of the pages folder, open the _app.tsx file.
Import the Box and Header components.
SessionProvider from Context.Your updated import statements should resemble the following:
<Component {...pageProps} /> with the Context SessionProvider. This ensures that each page has access to the React Context.Box component and place the Header and SessionProvider components inside it. You can view _app.tsx (GitHub).In the root of the pages folder, open index.tsx.
Import the Header component. You can view index.tsx (GitHub).
Now that you have synced up the database, your app should display information under Inventory Count, Variant Count, and Primary Category fields.
