Guide: Using Tria SDK in Next.js

This guide demonstrates how to integrate the Tria SDK into a Next.js application using dynamic import methods. We'll cover two approaches: using useEffect and using dynamic import().

Method 1: Using useEffect

In this method, we'll use the useEffect hook to dynamically import and initialize the Tria SDK after the component mounts.

Benefits:

  • Ensures the SDK is loaded only when needed
  • Allows for easier handling of side effects and cleanup
  • Works well with Next.js's client-side rendering

Example:

import { useState, useEffect } from 'react'

const TriaAuthComponent = () => {
  const [authManager, setAuthManager] = useState(null)

  useEffect(() => {
    let isMounted = true

    const loadTriaSDK = async () => {
      try {
        const TriaSDK = await import('@tria-sdk/authenticate-web')
        if (isMounted) {
          const manager = new TriaSDK.AuthManager({
            analyticsKeys: {
              clientId: 'YOUR_CLIENT_ID',
              projectId: 'YOUR_PROJECT_ID',
            },
          })
          setAuthManager(manager)
        }
      } catch (error) {
        console.error('Failed to load Tria SDK:', error)
      }
    }

    loadTriaSDK()

    return () => {
      isMounted = false
    }
  }, [])

  const handleLogin = async () => {
    if (authManager) {
      try {
            const handleLogin = (): void => {
              console.log("calling handleLogin");
              const resp = authManager.getAccount();
              console.log(resp);
            };

        authManager.subscribe("LOGIN_SUCCESS", handleLogin);

      } catch (error) {
        console.error('Login failed:', error)
      }
    }
  }

  return (
    <div>
      <h1>Tria Authentication</h1>
      <button onClick={handleLogin} disabled={!authManager}>
        Login
      </button>
    </div>
  )
}

export default TriaAuthComponent

Method 2: Using Dynamic Import

In this method, we'll use Next.js's dynamic import feature to load the Tria SDK component.

Benefits:

  • Leverages Next.js's built-in code splitting
  • Reduces initial bundle size
  • Allows for easier loading states

Example:

import dynamic from 'next/dynamic'
import { useState } from 'react'

const DynamicTriaAuth = dynamic(
  () => import('@tria-sdk/authenticate-web').then((mod) => mod.AuthManager),
  {
    ssr: false,
    loading: () => <p>Loading Tria SDK...</p>,
  },
)

const TriaAuthPage = () => {
  const [authManager, setAuthManager] = useState(null)

  const handleAuthManagerLoad = (loadedAuthManager) => {
    const manager = new loadedAuthManager({
      analyticsKeys: {
        clientId: 'YOUR_CLIENT_ID',
        projectId: 'YOUR_PROJECT_ID',
      },
    })
    setAuthManager(manager)
  }

const handleLogin = (): void => {
      console.log("calling handleLogin");
      const resp = authManager.getAccount();
      console.log(resp);
    };

authManager.subscribe("LOGIN_SUCCESS", handleLogin);


  return (
    <div>
      <h1>Tria Authentication</h1>
      <DynamicTriaAuth ref={handleAuthManagerLoad} />
      <button onClick={handleLogin} disabled={!authManager}>
        Login
      </button>
    </div>
  )
}

export default TriaAuthPage

Comparing the Methods

  1. useEffect Method:

    • Pros:
      • More control over when and how the SDK is loaded
      • Easier to handle loading states and errors manually
    • Cons:
      • Slightly more complex implementation
      • May introduce a brief delay before the SDK is available
  2. Dynamic Import Method:

    • Pros:
      • Leverages Next.js's built-in code splitting
      • Simpler implementation for basic use cases
      • Automatic loading state handling
    • Cons:
      • Less fine-grained control over the loading process
      • May be overkill for simple implementations

Best Practices

  1. Always handle loading and error states to provide a smooth user experience.
  2. Use environment variables for sensitive information like API keys.
  3. Implement proper typings if using TypeScript for better development experience.
  4. Consider using React Context or state management libraries for sharing the AuthManager instance across components.

By following this guide, you can effectively integrate the Tria SDK into your Next.js application using either dynamic import method, choosing the one that best fits your specific use case and project structure.

Was this page helpful?