How-To Guides & Tutorials

How to Integrate Intercom in Your Next.js 14 Project

how-to-integrate-intercom-in-your-nextjs-14-project

Fri Apr 26 2024

Intercom has become an indispensable tool for businesses looking to enhance their customer communication experience. Its real-time messaging capability allows you to engage with your customers directly and personally. If you're working with the latest Next.js 14, integrating Intercom into your project can supercharge your customer interactions. Here's a definitive guide crafted for tech enthusiasts who demand the best from their tools.

Prerequisites

  • A Next.js 14 project already up and running.
  • An active Intercom account and access to your unique app ID.

Step-by-Step Integration Guide

Integrating Intercom with Next.js 14 involves creating a dedicated component and embedding it within your layout structure. This process ensures that Intercom's scripts load efficiently, aligning with Next.js 14’s advanced script management capabilities.

Step 1: Creating the `IntercomClientComponent

First, we'll create a component dedicated to initializing Intercom in your application. Follow these steps:

  • Navigate to your components directory and create a new file named IntercomClientComponent.tsx
  • Copy and paste the following TypeScript code into your new component file:
    1// src/components/IntercomClientComponent.tsx    
    2
    3'use client';
    4import { useEffect } from "react";
    5const IntercomClientComponent: React.FC = () => {
    6    useEffect(() => {
    7        window.intercomSettings = {
    8            api_base: "https://api-iam.intercom.io",
    9            app_id: "{YOUR_INTERCOM_APP_ID}" // Replace with your Intercom app ID.
    10        };
    11        if (window.Intercom) {
    12            window.Intercom('reattach_activator');
    13            window.Intercom('update', intercomSettings);
    14        } else {
    15            const intercomScript = document.createElement('script');
    16            intercomScript.type = 'text/javascript';
    17            intercomScript.async = true;
    18            intercomScript.src = 'https://widget.intercom.io/widget/{YOUR_INTERCOM_APP_ID}'; // Ensure this matches your Intercom app ID.
    19            intercomScript.onload = () => window.Intercom('update', intercomSettings);
    20            document.body.appendChild(intercomScript);
    21        }
    22    }, []);
    23    return null; // This component does not render anything visually.
    24};
    25export default IntercomClientComponent;
    26
  • Replace `{YOUR_INTERCOM_APP_ID}` with your actual Intercom app ID.

Step 2: Integration within the layout.tsx

Now that your `IntercomClientComponent` is ready, it's time to integrate it into your project's layout. Here’s how you can do it:

  • Open or create your layout.tsx file within the src/layouts directory.
  • Add the IntercomClientComponent to your layout. Here’s an example layout implementing the component:
1// src/layouts/RootLayout.tsx
2 
3import React from "react";
4import Script from "next/script";
5import IntercomClientComponent from "@/components/IntercomClientComponent"; // Adjust the path as necessary.
6const RootLayout = ({children}: { children: React.ReactNode; }) => (
7    <html lang="en" className="h-full scroll-smooth">
8    <body className="relative h-full font-sans antialiased bg-white dark:bg-black text-black dark:text-white">
9    <main className="relative flex-col">
10        <div className="flex-grow flex-1 mt-20 min-h-screen">
11            {children}
12        </div>
13    </main>
14    <Script
15        strategy="afterInteractive"
16        id="intercom-settings"
17        dangerouslySetInnerHTML={{
18            __html: `
19                        window.intercomSettings = {
20                            api_base: "https://api-iam.intercom.io",
21                            app_id: "{YOUR_INTERCOM_APP_ID}", // Ensure this matches your actual Intercom app ID.
22                        };
23                    `
24        }}
25    />
26    <IntercomClientComponent/>
27    </body>
28    </html>
29);
30export default RootLayout;
31

Step-by-Step Guide for Dynamic Intercom Integration

Step 1: Modify IntercomClientComponent to Accept Props

First, modify the IntercomClientComponent to accept user information as props. This way, you can pass user data dynamically based on the user’s authentication state.

Updated IntercomClientComponent.tsx

1// src/components/IntercomClientComponent.tsx    
2
3'use client';
4import { useEffect } from "react";
5
6interface IntercomClientComponentProps {
7  userId?: string;
8  userEmail?: string;
9}
10
11const IntercomClientComponent: React.FC<IntercomClientComponentProps> = ({ userId, userEmail }) => {
12  useEffect(() => {
13    const intercomSettings: any = {
14      api_base: "https://api-iam.intercom.io",
15      app_id: "{YOUR_INTERCOM_APP_ID}" // Replace with your Intercom app ID.
16    };
17
18    if (userId && userEmail) {
19      intercomSettings.user_id = userId;
20      intercomSettings.email = userEmail;
21    }
22
23    window.intercomSettings = intercomSettings;
24
25    if (window.Intercom) {
26      window.Intercom('reattach_activator');
27      window.Intercom('update', intercomSettings);
28    } else {
29      const intercomScript = document.createElement('script');
30      intercomScript.type = 'text/javascript';
31      intercomScript.async = true;
32      intercomScript.src = 'https://widget.intercom.io/widget/{YOUR_INTERCOM_APP_ID}'; // Ensure this matches your Intercom app ID.
33      intercomScript.onload = () => window.Intercom('update', intercomSettings);
34      document.body.appendChild(intercomScript);
35    }
36  }, [userId, userEmail]);
37
38  return null; // This component does not render anything visually.
39};
40
41export default IntercomClientComponent;
42
43

Step 2: Update RootLayout to Pass User Data

Next, update your RootLayout component to pass the user data to IntercomClientComponent. This assumes you have a way to get the current user’s information (e.g., from context, a global state, or props). Updated RootLayout.tsx

1// src/layouts/RootLayout.tsx
2
3import React from "react";
4import Script from "next/script";
5import IntercomClientComponent from "@/components/IntercomClientComponent"; // Adjust the path as necessary.
6
7interface RootLayoutProps {
8  children: React.ReactNode;
9  userId?: string;
10  userEmail?: string;
11}
12
13const RootLayout: React.FC<RootLayoutProps> = ({ children, userId, userEmail }) => (
14  <html lang="en" className="h-full scroll-smooth">
15  <body className="relative h-full font-sans antialiased bg-white dark:bg-black text-black dark:text-white">
16  <main className="relative flex-col">
17    <div className="flex-grow flex-1 mt-20 min-h-screen">
18      {children}
19    </div>
20  </main>
21  <Script
22    strategy="afterInteractive"
23    id="intercom-settings"
24    dangerouslySetInnerHTML={{
25      __html: `
26                        window.intercomSettings = {
27                            api_base: "https://api-iam.intercom.io",
28                            app_id: "{YOUR_INTERCOM_APP_ID}", // Ensure this matches your actual Intercom app ID.
29                        };
30                    `
31    }}
32  />
33  <IntercomClientComponent userId={userId} userEmail={userEmail} />
34  </body>
35  </html>
36);
37
38export default RootLayout;

Step 3: Fetch and Pass User Data

Ensure you fetch the user’s data and pass it to the RootLayout component. Here’s an example assuming you use a context or some global state to manage user authentication:

Example of using Context to pass User Data

1import React, { createContext, useContext } from 'react';
2
3// Create a UserContext
4const UserContext = createContext<{ userId?: string; userEmail?: string }>({});
5
6// Example of providing user data in a higher component
7const MyApp: React.FC = ({ children }) => {
8  const user = { userId: 'user-123', userEmail: 'user@example.com' }; // Fetch user data here
9
10  return (
11    <UserContext.Provider value={user}>
12      <RootLayout userId={user.userId} userEmail={user.userEmail}>
13        {children}
14      </RootLayout>
15    </UserContext.Provider>
16  );
17};
18
19export default MyApp;

Optimizations and Best Practices

Integrating scripts like Intercom's requires consideration around performance and security. In Next.js 14, leveraging the built-in `Script` component or dynamic imports with proper event handling ensures optimal load times without sacrificing user experience or security.

Common Issues and Troubleshooting

When integrating third-party services, issues can arise:

  • Errors in the Intercom Event Handlers: Ensure that your component lifecycle management aligns with Intercom's API expectations.
  • Script Loading Issues: Verify that your script tags are loading after interactive DOM elements to prevent render blocking.

Effective integration of Intercom within your Next.js 14 project not only elevates your user engagement but also leverages the state-of-the-art features offered by both platforms. This guide should serve as a comprehensive resource for integrating customer communication seamlessly into your digital project.

We encourage feedback and dialogue among our tech enthusiast community. Share your thoughts, experiences, or inquiries below. Happy coding!

Feedback and Community Contributions

We highly value the input and contributions from our developer community. If you have implemented Intercom in your Next.js projects and have insights, optimizations, or solutions that differ from this guide, please contribute to our repository. Community-driven advancements help us all to grow and improve our implementations. https://github.com/tantainnovative/intercom-next-js-14-guide

Future Directions

With the rapid evolution of web technologies, Next.js and Intercom will undoubtedly introduce new features and improvements. We aim to keep this guide updated with the latest best practices and encourage the community to participate in sharing updates and new techniques. Stay tuned for future revisions as we continue to explore more efficient, secure, and user-friendly integration methods.