Install with Next.js or React app

Instructions on how to deploy Fairing on your or Next.js or React application.

Step 1: Create React hook

To integrate Fairing's post-checkout survey into your React or NextJS application, you'll use a custom hook that handles loading and initializing the Fairing SDK. This hook will automatically load the Fairing script, initialize it with your API credentials, and display the survey to your customers.

The hook manages the entire lifecycle of the Fairing SDK, including cleanup when the component unmounts, making it safe to use across different pages in your application.

// @/hooks/useFairing.ts

import { useEffect } from 'react';

interface UseFairingOptions {
  apiKey: string;
  customerId: string;
}

declare global {
  interface Window {
    Fairing: any;
  }
}

export function useFairing({ apiKey, customerId }: UseFairingOptions) {
  useEffect(() => {
    if (!apiKey || !customerId) {
      console.log("Could not initialize Fairing SDK, missing apiKey or customerId");
      return;
    }

    const loadFairingSDK = () => {
      const script = document.createElement('script');
      script.src = `https://sdk.fairing.co/sdk/1.0.0-beta/fairing-1.0.0-beta.js?t=${Date.now()}`;
      script.id = 'fairing-sdk';
      script.type = 'module';
      script.defer = true;

      script.onload = () => {
        window.Fairing = window.Fairing(apiKey, customerId, {
          config: { dismissible: true },
        });
        window.Fairing.nextQuestion();
        console.log('Fairing SDK loaded and initialized');
      };

      script.onerror = () => {
        console.error('Failed to load Fairing SDK');
      };

      document.head.appendChild(script);
    };

    loadFairingSDK();

    return () => {
      const existingScript = document.getElementById('fairing-sdk');
      if (existingScript) {
        existingScript.remove();
      }
    };
  }, [apiKey, customerId]);
}

Step 2: Use the hook

Once you have the useFairing hook set up, you can use it on any page where you want to display the post-checkout survey. Simply import the hook and call it with your API credentials.

Here's how to implement it:

'use client'

// On your imports add:
import { useFairing } from "@/hooks/useFairing";

export default function OrderConfirmation() {
  useFairing({
    apiKey: "PUT YOUR API KEY HERE",
    customerId: "PUT YOUR CUSTOMER ID OR EMAIL HERE"
  });
  ...
  return (
    ...
  );
}

The survey will appear once you load the page:

Step 3: Configure your Fairing survey

Fairing's SDK can be configured with additional options. When using React or Next.js you need to configure these options on your hook:

// useFairing.ts
script.onload = () => {
  window.Fairing = window.Fairing(apiKey, customerId, {
		// Pass any additional options inside this object:
    config: { dismissible: true },
		integrations: { ga: true }
  });
  window.Fairing.nextQuestion();
  console.log('Fairing SDK loaded and initialized');
};