Add MagicChat to Your Next.js Application

MagicChat provides a simple way to add AI-powered chat to your Next.js application using our JavaScript widget. No package installation required - just add our script to your application.

Prerequisites

  • A Next.js project (version 13 or higher)
  • A MagicChat account and bot ID (Sign up here)
  • Basic knowledge of React and TypeScript

Implementation

"use client";

import React, { useEffect } from 'react';
import { usePathname } from 'next/navigation';

export default function ChatbotWidget() {
  const pathname = usePathname();

  // Check if current path should exclude chatbot
  const shouldExcludeChatbot = () => {
    const excludedPaths = ['/admin/', '/dashboard/']; // Add paths where you don't want the chatbot
    return excludedPaths.some(path => pathname.startsWith(path));
  };

  useEffect(() => {
    // Skip widget initialization if we're in a server environment or on excluded paths
    if (typeof window === 'undefined' || shouldExcludeChatbot()) return;

    // Check if the script is already loaded
    const existingScript = document.getElementById('magicchat-widget-script');
    if (existingScript) return;

    // Create and load the script
    const script = document.createElement('script');
    script.id = 'magicchat-widget-script';
    script.src = 'https://script.magicchat.ai/js/commandk.js';
    script.setAttribute('id', 'YOUR_BOT_ID');
    
    // Append the script to the document
    document.body.appendChild(script);

    // Cleanup function to remove the script when component unmounts
    return () => {
      const scriptToRemove = document.getElementById('magicchat-widget-script');
      if (scriptToRemove && scriptToRemove.parentNode) {
        scriptToRemove.parentNode.removeChild(scriptToRemove);
      }
    };
  }, [pathname]);

  // This component doesn't render anything visible
  return null;
}

Add to Layout

Root Layout Integration

Add the ChatbotWidget component to your root layout

// app/layout.tsx
import ChatbotWidget from '@/components/ChatbotWidget';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        {children}
        <ChatbotWidget />
      </body>
    </html>
  );
}

Advanced Configuration

Customization Options

  • Theme customization through CSS variables
  • Custom chat window position
  • Initial messages and prompts
  • Custom avatar and branding

Next Steps

Need Help?

If you need assistance with integration or have any questions, feel free to: