Connection Creation

The Datagrid API provides an iframe-based embedding solution for connection creation that allows you to integrate third-party service authentication flows directly into your application.

Overview

When you need to create connections to third-party services (like Google Drive, Hubspot, Dropbox, etc.), you can embed the Datagrid API connection creation flow in an iframe. The iframe will handle the OAuth flow and authentication, then communicate the results back to your parent application via postMessage events.

Basic Implementation

Here’s a React component example that demonstrates how to embed the connection creation iframe:
import React, { FC, useRef, useEffect, useState } from "react";
import { Typography, Box } from "@mui/material";
import makeStyles from "@mui/styles/makeStyles";

const useStyles = makeStyles((theme) => ({
  root: {
    height: "100%",
    width: "100%",
    flex: 1,
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
  },
  iframeWrapper: {
    display: "flex",
    flexDirection: "column",
    gap: theme.spacing(4),
  },
  iframe: {
    border: "none",
    borderRadius: theme.spacing(1),
    boxShadow: theme.shadows[2],
  },
}));

interface ConnectionEmbedProps {
  redirectUrl: string;
  onConnectionCreated?: (connection: any) => void;
  onConnectionUpdated?: (connection: any) => void;
  onError?: (error: any) => void;
}

const ConnectionEmbed: FC<ConnectionEmbedProps> = ({
  redirectUrl,
  onConnectionCreated,
  onConnectionUpdated,
  onError,
}) => {
  const classes = useStyles();
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const [iframeHeight, setIframeHeight] = useState(600);

  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      // Only process messages from datagrid-api
      if (!event.data.type || !event.data.type.includes("datagrid-api")) {
        return;
      }

      console.log("Received iframe message:", event.data);

      switch (event.data.type) {
        case "datagrid-api/connection-created":
          console.log("Connection created:", event.data.payload);
          onConnectionCreated?.(event.data.payload);
          break;

        case "datagrid-api/connection-updated":
          console.log("Connection updated:", event.data.payload);
          onConnectionUpdated?.(event.data.payload);
          break;

        case "datagrid-api/error":
          console.error("Iframe error:", event.data.payload);
          onError?.(event.data.payload);
          break;

        case "datagrid-api/resize":
          const { height, width } = event.data.payload;
          setIframeHeight(height);
          console.log(`Iframe resized to: ${width}x${height}`);
          break;

        case "datagrid-api/content-loaded":
          console.log("Iframe content loaded");
          break;

        default:
          console.log("Unknown iframe event:", event.data.type);
      }
    };

    window.addEventListener("message", handleMessage);

    return () => {
      window.removeEventListener("message", handleMessage);
    };
  }, [onConnectionCreated, onConnectionUpdated, onError]);

  return (
    <div className={classes.root}>
      <div className={classes.iframeWrapper}>
        <Typography variant="h6">Connect Your Service</Typography>
        <iframe
          className={classes.iframe}
          ref={iframeRef}
          src={redirectUrl}
          width="400px"
          height={`${iframeHeight}px`}
          title="Connection Creation"
        />
      </div>
    </div>
  );
};

export default ConnectionEmbed;

Usage Example

import ConnectionEmbed from "./ConnectionEmbed";

function App() {
  const [redirectUrl, setRedirectUrl] = useState("");

  useEffect(() => {
    const initConnection = async () => {
      try {
        const { redirect_url } = await datagridClient.connections.create({
          connector_id: "google_drive",
        });
        setRedirectUrl(redirect_url);
      } catch (err) {
        console.error("Failed to create connection:", err);
      }
    };

    initConnection();
  }, []);
  const handleConnectionCreated = (connection) => {
    console.log("New connection:", connection);
    // Handle the newly created connection
    // You can store it, redirect user, etc.
  };

  const handleError = (error) => {
    console.error("Connection error:", error);
    // Handle any errors that occur during connection creation
  };

  if (!redirectUrl) {
    return <noscript />;
  }

  return (
    <ConnectionEmbed
      redirectUrl={redirectUrl}
      onConnectionCreated={handleConnectionCreated}
      onError={handleError}
    />
  );
}

Message Events

The iframe will send various postMessage events to the parent window. All events follow this structure:
interface IFrameEvent {
  type: string;
  payload: any;
}

Available Event Types

datagrid-api/connection-created

Emitted when a new connection is successfully created. Payload:
{
  object: "connection",
  id: string,
  name: string,
  teamspace_id: string,
  connection_id: string,
  valid: boolean,
  value: string,
  created_at: string,
  updated_at: string
}

datagrid-api/connection-updated

Emitted when an existing connection is successfully updated. Payload: Same as connection-created event.

datagrid-api/error

Emitted when an error occurs during the connection process. Payload:
{
  message: string,
  error: object | null
}

datagrid-api/resize

Emitted when the iframe needs to be resized to accommodate content. Payload:
{
  height: number,
  width: number
}

datagrid-api/content-loaded

Emitted when the iframe content has finished loading. Payload: null

Security Considerations

  • Always validate the origin of postMessage events to ensure they come from your expected domain
  • Implement proper error handling for all message types
  • Consider implementing a timeout mechanism for connection creation
  • Store connection credentials securely after successful creation

Best Practices

  1. Event Filtering: Always check that messages are from the expected source and contain the datagrid-api prefix
  2. Error Handling: Implement comprehensive error handling for all possible error scenarios
  3. User Feedback: Provide clear feedback to users about the connection status
  4. Responsive Design: Handle iframe resizing events to provide a smooth user experience
  5. Loading States: Show appropriate loading states while the iframe is initializing

Creating a Connection

To get the redirect URL, call the createConnection endpoint with the desired connector ID: