The instructions vary depending on the router you use.
Since the Firmhouse JS SDK relies on the DOMContentLoaded event for initialization by default, it is important to ensure that we initialize the SDK before this event occurs. Next.js provides us with the beforeInteractive strategy for loading scripts before this event.
If you are using Pages Router, you can use the following template to add the Firmhouse JS SDK to your Next.js app.
You need to set theNEXT_PUBLIC_STOREFRONT_API_TOKEN environment variable to your Storefront API token. Follow this guide to find out how to get one.
As DOMContentLoaded event triggers before third party scripts are injected on Next.js with App router, we need to manually initialize Storefront SDK.
If you are using App Router you can use the following template to add the Firmhouse JS SDK to your Next.js app.
You need to set theNEXT_PUBLIC_STOREFRONT_API_TOKEN environment variable to your Storefront API token. Follow this guide to find out how to get one.
FirmhouseProvider.jsx
"use client";import { useState, createContext } from"react";import Script from"next/script";exportconstFirmhouseContext=createContext();exportdefaultfunctionFirmhouseProvider({ children }) {const [firmhouse,setFirmhouse] =useState(null);conststorefrontToken=process.env.NEXT_PUBLIC_STOREFRONT_API_TOKEN;return ( <> <Scriptsrc="https://storefrontjs.firmhouse.com/dist/storefront.js"onLoad={() => {// Here we initialize Firmhouse manually using initializeFirmhouse functionwindow.initializeFirmhouse({ storefrontToken, });setFirmhouse(window.Firmhouse); }} /> <FirmhouseContext.Providervalue={{ firmhouse }}> {children} </FirmhouseContext.Provider> </> );}
Instead of depending on DOMContentLoaded event, we use window.initializeFirmhouse function to set up firmhouse. Then we create a context to pass the Firmhouse object to child components.