Apps
Tutorial: Next.js starter app
Step 2: Connect your app to BigCommerce

Step 2: Connect Your App to BigCommerce

In this step, you connect your app to the BigCommerce ecosystem embedding it into Draft Apps.

Install node-bigcommerce

To authenticate and use your app with the BigCommerce API, install BigCommerce's in-house node-bigcommerce module (GitHub) (opens in a new tab).

Install node client
npm install github:bigcommerce/node-bigcommerce

View tested package versions

You can view a list of all the tested package versions in the package.json file on the Step 2 branch (opens in a new tab) of this sample app's repo.

Setup the auth lib page

  1. In the root directory of your app, create a lib folder.

  2. In the lib folder, create an auth.ts file.

  3. Open the auth.ts file and add the BigCommerce import at the top of the file.

Add imports auth.ts
import * as BigCommerce from 'node-bigcommerce';
  1. Create a BigCommerce instance required as part of the authorization step when first installing the application.
Create BC instance auth.ts
// Create BigCommerce instance
// https://github.com/bigcommerce/node-bigcommerce/
const bigcommerce = new BigCommerce({
    logLevel: 'info',
    clientId: process.env.CLIENT_ID,
    secret: process.env.CLIENT_SECRET,
    callback: process.env.AUTH_CALLBACK,
    responseType: 'json',
    headers: { 'Accept-Encoding': '*' },
    apiVersion: 'v3'
});
 
const bigcommerceSigned = new BigCommerce({
    secret: process.env.CLIENT_SECRET,
    responseType: 'json'
});
 
interface QueryParams {
    [key: string]: string;
}

The bigcommerceSigned function is called when loading or uninstalling the application.

  1. Export the getBCAuth function.
Export getBCAuth auth.ts
export function getBCAuth(query: QueryParams) {
    return bigcommerce.authorize(query);
}

You use the authorize method for the /auth API endpoint which gets called when you install or update the app. The authorize method retrieves your permanent access token and returns it in the data object.

  1. Export the getBCVerify function.
Exports getBCVerify auth.ts
export function getBCVerify({ signed_payload_jwt }: QueryParams) {
    return bigcommerceSigned.verifyJWT(signed_payload_jwt);
}

The verifyJWT method employs the signed_payload_jwt query parameter to authenticate requests. You use the verifyJWT method for both /load and /uninstall API endpoints. To learn more about the OAuth flow, see Single-Click App OAuth Flow.

You can view auth.ts (GitHub) (opens in a new tab).

Add API endpoints

Next.js maps all APIs that are part of the Next.js application to the /api/* route. You can take advantage of it by creating a sub-directory within the pages folder called api. This signals Next.js to treat files within /pages/api as API endpoints and automatically handle their routing. To learn more about Next.js API routes, see API Routes (opens in a new tab).

  1. In the pages folder, create an api folder.

  2. Open the api folder and add the following files: auth.ts, load.ts, and uninstall.ts.

  3. Open the auth.ts file and add the logic to authorize the app. You can view auth.ts (GitHub) (opens in a new tab).

Add logic auth.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { getBCAuth } from '../../lib/auth';
 
export default async function auth(req: NextApiRequest, res: NextApiResponse) {
    try {
        // First, authorize the application
        // req.query: query param passed from the Control Panel to your app
        await getBCAuth(req.query);
        // Once the app has been authorized, redirect to the homepage (/pages/index.tsx)
        res.redirect(302, '/');
    } catch (error) {
        const { message, response } = error;
        res.status(response?.status || 500).json({ message });
    }
}

The /auth endpoint gets called when installing the app. Launching (loading) or uninstalling the app will not call the /auth endpoint.

  1. Open the load.ts file and add the logic to sign the user in when the app calls the /load endpoint (when launching the app). You can view load.ts (GitHub) (opens in a new tab).
Add logic load.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { getBCVerify } from '../../lib/auth';
 
export default async function load(req: NextApiRequest, res: NextApiResponse) {
    try {
        await getBCVerify(req.query);
 
        res.redirect(302, '/');
    } catch (error) {
        const { message, response } = error;
        res.status(response?.status || 500).json({ message });
    }
}
  1. Open the uninstall.ts file and add the logic to remove a user who has uninstalled the application from their BigCommerce account. You can view uninstall.ts (GitHub) (opens in a new tab).
Add logic uninstall.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { getBCVerify } from '../../lib/auth';
 
export default async function uninstall(req: NextApiRequest, res: NextApiResponse) {
    try {
        await getBCVerify(req.query);
 
        res.status(200).end();
    } catch (error) {
        const { message, response } = error;
        res.status(response?.status || 500).json(message);
    }
}

Create an HTTPS tunnel

To connect your sample app to BigCommerce, you need a publicly accessible URL. To add network access while still in the development phase, you can use ngrok (opens in a new tab), a free tool that lets you expose local servers like localhost:3000 to the public internet over secure tunnels.

  1. Open a new terminal window and install ngrok (opens in a new tab) using Homebrew.
brew install ngrok/ngrok/ngrok
ngrok config add-authtoken <TOKEN>
  1. Expose the web server to the internet.
ngrok http http://localhost:8080              # Start the app
  1. You should see the ngrok web interface. Copy the HTTPS tunnel URL and keep the app running. Your terminal should display a message similar to the following:

https tunnel

Ngrok configuration

Although you can use the ngrok npm package without creating an account, any unauthenticated tunnels you create will expire after two hours. For the best development experience, create a free ngrok account (opens in a new tab), find your ngrok authtoken (opens in a new tab), and add the authtoken (opens in a new tab) to your global ngrok configuration.

Register the draft app

To register an app, you need a BigCommerce store. If you do not have a BigCommerce store, visit the BigCommerce Pricing (opens in a new tab) page to start a free trial.

  1. In your Developer Portal (opens in a new tab) account, click Create an app.

Create an app

  1. Enter app details at the prompts. Because you are building a sample app, you can name it anything you want. Production-level apps should meet the general requirements outlined in Approval Requirements.

  2. Click Technical.

  3. Under App Features, select STORE OWNER for Multiple Users and SINGLE-CLICK for App Type.

  4. To fill out Callback URLs, retrieve the public HTTPS URL of your ngrok tunnel.

HTTPS URL

⚠️

Use the secure tunnel

Avoid using the unsecured HTTP URL to prevent security policy errors.

  • For Auth Callback URL, enter the ngrok URL of your app followed by /api/auth.
  • For Load Callback URL, enter the ngrok URL of your app followed by /api/load.
  • For Uninstall Callback URL, enter the ngrok URL of your app followed by /api/uninstall.

Callback URL

Next.js route mapping

Next.js maps all APIs that are part of the Next.js application to the /api/* route. To learn more about Next.js API routes, see API Routes (opens in a new tab).

  1. Because you will be modifying the Products API resource, set the Products OAuth scope to MODIFY. To learn more about the available OAuth scopes, see OAuth scopes.

OAuth scopes

  1. Click Update & Close.

  2. Select Confirm Update.

You should see your app listed under My Apps in your Developer Portal account.

Add your client ID and client secret

It is best practice to declare environment variables in the .env environment file. You use the .env file to store your Client ID and Client Secret Key.

Next.js comes pre-equipped to handle environment variables. It loads environment variables from .env.local into process.env, allowing you to use them in Next.js data fetching and API routes. To learn more, see Next.js Environment Variables (opens in a new tab).

  1. Create an .env file in the root directory of your app.

  2. Add the app's credentials and auth callback placeholders to the .env file.

Initial contents .env
CLIENT_ID={app client id}
CLIENT_SECRET={app secret}
 
AUTH_CALLBACK=https://{ngrok_url}/api/auth
 
# Most users do not need to change this
API_URL=api.bigcommerce.com
⚠️

Don't commit authentication credentials

Never share sensitive data such as API keys and passwords publicly. Avoid committing them to your repository.

  1. Navigate to Developer Portal > My Apps (opens in a new tab). Locate your app and click View Client ID to retrieve your app's credentials.
  2. Copy the app's client ID and client secret and paste them into the .env file.
  3. Update AUTH_CALLBACK in .env with your {ngrok_url}. Because env variables are loaded on build, make sure to save your changes.
  4. Switch to the terminal window where the dev server is currently running and restart the dev environment.
Restart dev server
npm run dev

Ngrok expiration and callbacks

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.

Install and launch the app

  1. Sign in to your BigCommerce store and navigate to Apps > My Apps > My Draft Apps (opens in a new tab). You should see your new app displayed under My Draft Apps.

My draft apps

  1. Click the app's name.

  2. Click Install.

  3. Click Confirm.

You should see your app embedded in the BigCommerce platform.

Embedded app

Next: Integrate the BigCommerce API and Add a Database

Did you find what you were looking for?