Troubleshooting

Troubleshooting

Solutions to common issues with Produck SDK.

Installation Issues

Package not found

Error:

npm ERR! 404 Not Found - GET https://registry.npmjs.org/@produck%2fsdk

Solution:

  1. Check package name is correct: @produck/sdk
  2. Verify you have internet connection
  3. Try clearing npm cache: npm cache clean --force
  4. Check npm registry: npm config get registry

TypeScript errors on import

Error:

Could not find a declaration file for module '@produck/sdk'

Solution: The SDK includes TypeScript definitions. If you're seeing this:

  1. Restart your TypeScript server
  2. Check tsconfig.json includes:
    {
      "compilerOptions": {
        "skipLibCheck": true,
        "esModuleInterop": true
      }
    }

Build errors with Next.js

Error:

Module not found: Can't resolve '@produck/sdk/react'

Solution: Ensure you're using Next.js 13+ and have proper imports:

// ✅ Correct
import { ProduckProvider } from '@produck/sdk/react';
 
// ❌ Wrong
import { ProduckProvider } from '@produck/sdk';

SDK Initialization

"SDK not initialized" error

Error:

Error: SDK not initialized. Call init() first.

Cause: Trying to use SDK methods before calling init().

Solution:

// ❌ Wrong
const produck = createProduck({ sdkKey: 'key' });
produck.register('action', handler); // Error!
 
// ✅ Correct
const produck = createProduck({ sdkKey: 'key' });
await produck.init(); // Wait for initialization
produck.register('action', handler); // Now it works

For React:

function Component() {
  const isReady = useProduckReady();
  
  if (!isReady) {
    return <div>Loading...</div>;
  }
  
  // SDK is ready, safe to use
  return <YourContent />;
}

"Failed to create session" error

Error:

Error: Failed to create session: 401

Causes:

  • Invalid SDK key
  • SDK key for wrong environment
  • Network/firewall issues

Solutions:

  1. Verify SDK key:

    # Check your .env file
    cat .env.local | grep SDK_KEY
  2. Check key format:

    Should start with: sdk_proj_
    Example: sdk_proj_1a2b3c4d5e6f
  3. Test API connectivity:

    curl https://api.produck.io/health
  4. Check for typos:

    // Common typo
    sdkKey: process.env.NEXT_PUBLIC_SDK_KEy // Missing Y
     
    // Correct
    sdkKey: process.env.NEXT_PUBLIC_SDK_KEY

Timeout errors

Error:

Error: Request timeout

Solutions:

  1. Check internet connection
  2. Verify API URL is correct
  3. Check for corporate firewall blocking requests
  4. Try pinging the API:
    curl -v https://api.produck.io/api/v1/health

React Integration Issues

Context errors

Error:

Error: useProduckAction must be used within ProduckProvider

Cause: Using hooks outside ProduckProvider.

Solution:

// ❌ Wrong
function App() {
  useProduckAction('test', handler); // Error!
  
  return (
    <ProduckProvider config={{sdkKey: 'key'}}>
      <Content />
    </ProduckProvider>
  );
}
 
// ✅ Correct
function App() {
  return (
    <ProduckProvider config={{sdkKey: 'key'}}>
      <Content />
    </ProduckProvider>
  );
}
 
function Content() {
  useProduckAction('test', handler); // Works!
  return <div>Content</div>;
}

Hooks not re-rendering

Issue: Component doesn't update when SDK state changes.

Solution: Make sure you're using Produck hooks:

// ❌ Won't re-render
const { sdk } = useProduck();
const messages = sdk?.messages; // Direct access
 
// ✅ Will re-render
const { messages } = useProduck(); // Via context

Handler not firing

Issue: Action registered but not triggering.

Debugging steps:

  1. Check operation ID:

    // Must match exactly (case-sensitive)
    useProduckAction('open-contact', handler);
    // Dashboard operation_id: "open-contact" ✅
    // Dashboard operation_id: "open_contact" ❌
  2. Verify SDK is ready:

    const isReady = useProduckReady();
    console.log('SDK Ready:', isReady); // Should be true
  3. Check handler is called:

    useProduckAction('test', (payload) => {
      console.log('🔥 Handler fired!', payload);
    });
  4. Test with simple handler:

    useProduckAction('test', () => {
      alert('It works!');
    });

Dependency array issues

Issue: Handler doesn't use latest state.

Problem:

function Component() {
  const [count, setCount] = useState(0);
  
  // ❌ Handler always sees count = 0
  useProduckAction('increment', () => {
    console.log(count); // Always 0
  }, []); // Empty deps
  
  return <div>{count}</div>;
}

Solution:

// ✅ Handler sees latest count
useProduckAction('increment', () => {
  console.log(count); // Current value
}, [count]); // Include count in deps

Operation Issues

Operations not matching

Issue: User message doesn't trigger operation.

Debugging:

  1. Test in dashboard:

    • Go to your operation
    • Click "Test"
    • Try your trigger phrases
    • Check match confidence
  2. Check trigger phrases:

    // Too specific
    "contact support right now"
     
    // Better (more flexible)
    "contact support"
    "get in touch"
    "need help"
  3. Try synonyms:

    // If "pricing" doesn't match, try:
    "show pricing"
    "see prices"
    "how much"
    "cost information"
  4. Check for typos:

    • Review trigger phrases for spelling errors
    • Test variations in dashboard first

Multiple operations matching

Issue: Wrong operation triggers.

Cause: Overlapping trigger phrases.

Solution:

  1. Make trigger phrases more specific:

    // ❌ Overlapping
    Operation 1: "contact"
    Operation 2: "contact form"
     
    // ✅ Distinct
    Operation 1: "contact support", "get help"
    Operation 2: "fill contact form", "submit inquiry"
  2. Review all operations:

    • List all trigger phrases
    • Look for similarities
    • Make each operation unique

Operation returns unexpected data

Issue: payload.actionConfig is empty or wrong.

Cause: Configuration not set in dashboard.

Solution:

  1. Edit operation in dashboard

  2. Set actionConfig JSON:

    {
      "productId": "123",
      "variant": "premium"
    }
  3. Access in handler:

    useProduckAction('show-product', (payload) => {
      const productId = payload.actionConfig.productId;
    });

Chat Widget Issues

Widget not visible

Checklist:

  1. Provider is rendering:

    <ProduckProvider config={{sdkKey: 'key'}}>
      <App />
      <ProduckChat /> {/* Make sure this is rendered */}
    </ProduckProvider>
  2. Check z-index conflicts:

    /* Your header might be covering the widget */
    .my-header {
      z-index: 9999; /* Higher than widget */
    }

    Solution:

    <ProduckChat style={{ zIndex: 10000 }} />
  3. Check position:

    // Widget might be off-screen
    <ProduckChat position="bottom-right" /> {/* Try different positions */}
  4. Inspect with DevTools:

    • Open browser DevTools
    • Check if widget exists in DOM
    • Look for CSS issues

Widget styling issues

Issue: Widget looks broken or unstyled.

Solutions:

  1. Check for CSS conflicts:

    /* Your global CSS might be affecting widget */
    * {
      all: unset; /* Don't do this! */
    }
  2. Use custom styling:

    <ProduckChat
      theme="dark"
      primaryColor="#8b5cf6"
      className="custom-chat"
    />
  3. Override with CSS:

    .produck-chat-widget {
      /* Custom styles */
    }

Messages not sending

Issue: Type message, click send, nothing happens.

Debug:

  1. Check console for errors:

    // Look for error messages
  2. Verify SDK is initialized:

    const isReady = useProduckReady();
    console.log('Ready:', isReady);
  3. Test programmatically:

    const { sendMessage } = useProduckMessages();
     
    const testSend = async () => {
      try {
        await sendMessage('test');
        console.log('✅ Message sent');
      } catch (error) {
        console.error('❌ Send failed:', error);
      }
    };

Network Issues

CORS errors

Error:

Access to fetch at 'https://api.produck.io' from origin 'http://localhost:3000'
has been blocked by CORS policy

Solutions:

  1. Use correct API URL:

    // Development
    apiUrl: 'http://localhost:4001/api/v1'
     
    // Production
    apiUrl: 'https://api.produck.io/api/v1'
  2. Check environment variables:

    # Make sure NEXT_PUBLIC_ prefix for client-side
    NEXT_PUBLIC_API_URL=https://api.produck.io/api/v1
  3. Contact support if CORS persists:

Rate limiting

Error:

429 Too Many Requests

Solutions:

  1. Implement debouncing:

    const debouncedSend = debounce(async (msg) => {
      await produck.sendMessage(msg);
    }, 500);
  2. Cache responses:

    const cache = new Map();
     
    const sendWithCache = async (msg) => {
      if (cache.has(msg)) {
        return cache.get(msg);
      }
      const response = await produck.sendMessage(msg);
      cache.set(msg, response);
      return response;
    };
  3. Upgrade your plan:

    • Check current limits in dashboard
    • Consider upgrading for higher limits

TypeScript Issues

Type errors with payload

Error:

Property 'productId' does not exist on type 'Record<string, any>'

Solution:

Define custom types:

interface MyActionConfig {
  productId: string;
  variant: string;
}
 
interface MyActionPayload extends ActionPayload {
  actionConfig: MyActionConfig;
}
 
useProduckAction('show-product', (payload: MyActionPayload) => {
  const productId = payload.actionConfig.productId; // Typed!
});

Module resolution errors

Error:

Cannot find module '@produck/sdk/react'

Solution:

Update tsconfig.json:

{
  "compilerOptions": {
    "moduleResolution": "bundler", // or "node16"
    "esModuleInterop": true
  }
}

Performance Issues

Slow initialization

Issue: init() takes too long.

Solutions:

  1. Show loading state:

    const isReady = useProduckReady();
    if (!isReady) return <LoadingScreen />;
  2. Check network:

    • Test API speed: curl -w "@curl-format.txt" -s https://api.produck.io/health
    • Check latency to API server
  3. Optimize bundle:

    // Code split if not needed immediately
    const ProduckChat = lazy(() => 
      import('@produck/sdk/react').then(m => ({ default: m.ProduckChat }))
    );

Memory leaks

Issue: Memory usage grows over time.

Solution:

Always clean up:

// React
useEffect(() => {
  produck.register('action', handler);
  return () => produck.unregister('action'); // Cleanup!
}, []);
 
// Vanilla JS
produck.register('action', handler);
// Later:
produck.unregister('action');
produck.destroy(); // On app unmount

Getting Help

Enable debug mode

const produck = createProduck({
  sdkKey: 'key',
  onAction: (key, payload) => {
    console.log('[DEBUG] Action:', key, payload);
  },
  onMessage: (msg) => {
    console.log('[DEBUG] Message:', msg);
  },
  onError: (err) => {
    console.error('[DEBUG] Error:', err);
  }
});

Collect diagnostic info

When reporting issues, include:

  1. SDK version:

    npm list @produck/sdk
  2. Environment:

    • Browser & version
    • Framework & version
    • Node.js version
  3. Code sample:

    • Minimal reproduction
    • Relevant configuration
  4. Console output:

    • Errors
    • Warnings
    • Debug logs

Contact support

Check status

Still stuck?