Using with Next.js
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.
import Script from "next/script";
export default function Page() {
const firmhouseConfig = {
storefrontToken: process.env.NEXT_PUBLIC_STOREFRONT_API_TOKEN,
};
return (
<main>
<Script strategy="beforeInteractive">
{`window.Firmhouse = ${JSON.stringify(firmhouseConfig)}`}
</Script>
<Script
src="https://storefrontjs.firmhouse.com/dist/storefront.js"
strategy="beforeInteractive"
/>
<button
onClick={() => {
window.Firmhouse.showCart();
}}
>
Show cart
</button>
</main>
);
}
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.
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.
Here, we access firmhouse object from the context we created.
To provide, context value to children we need to wrap the components that needs to use firmhouse object with FirmhouseProvider.
Last updated
Was this helpful?