For synchronous data import/exchange completed in one session, create a new Space each time Flatfile is opened. This suits situations where a clean slate for every interaction is preferred.

Before you begin

Get your keys

To complete this tutorial, you'll need to retrieve your Publishable key from your development environment.

Note: The Publishable Key is safe to be used in client-side applications as it has limited access to the Flatfile API.

Prepare your project

Install packages

Make a new directory.

mkdir example-flatfile-js-embed

Go into that directory.

cd example-flatfile-js-embed

Follow prompts from the init command.

npm init

Install packages. (We’ll use parcel for bundling.)

npm i @flatfile/javascript @flatfile/listener @flatfile/plugin-record-hook @flatfile/api flatfile

Install dev packages.

npm i parcel --save-dev

Create your file structure

Setup your app to look something like this:

├── public/
   └── index.html
   └── styles.css
├── src/
   └── client.js
   └── workbook.js
   └── listener.js
├── package.json <--- already created
└── package-lock.json <--- already created

In this file structure, your app should have two main directories, public and src.

The public directory contains the index.html file, which is the entry point of the application’s front-end, and the styles.css file for styling the iframe.

The src directory contains the main components and logic of the application, including the client.js file, which initializes Flatfile and passes in available options.

Build your importer

1. Add a Flatfile button

Add a button to your application to open Flatfile in a modal. Pass in your publishableKey and a new Space will be created on each page load. Also, add the content here to your styles.css.

2. Initialize Flatfile

In your client.js, at minimum, you’ll need to receive the publishableKey set from when you called openFlatfile.

src/client.js
import { initializeFlatfile } from '@flatfile/javascript';

//create a new space in modal
window.openFlatfile = ({ publishableKey }) => {
  if (!publishableKey) {
    throw new Error(
      'You must provide a publishable key - pass through in index.html'
    );
  }
  const flatfileOptions = {
    name: 'Embedded Space',
    publishableKey,
    sidebarConfig: {
      showSidebar: false,
    },
    closeSpace: {
      operation: 'submitActionFg',
      onClose: () => {
        //custom code if needed
      },
    },
    // Additional props...
  };

  initializeFlatfile(flatfileOptions);
};

3. Start your client

Now, start your front end by heading to terminal and running the following command. To see that it’s running, visit: https://localhost:1234 (or the port it is running on) and you should see your page and a button. Click the button and see that an empty Space gets created.

npx parcel public/index.html

4. Build a Workbook

Now, let's build a Workbook inside the Space for next time.

  1. Update your workbook.js with this simple Blueprint.
  2. Update client.js to import the Workbook.

Next time you open Flatfile, you'll see a Workbook called "Contacts" that has one Sheet with three fields. Your Workbook will also have a Submit action. We will configure this action in the next step.

5. Transform Data

Next, we'll listen for data changes and respond using an event listener.

  1. Update your listener.js with this simple recordHook.
  2. Update client.js to import the listener.

Once you add this code, when a change occurs, we'll log the entered first name and update the last name to "Rock." You'll immediately see this begin to work when you add or update any records. Learn more about Handling Data

6. Match your brand

By attaching a themeConfig to flatfileOptions in src/client.js, we will now override colors in your Space to match your brand. See all of the options here in the Theming Reference.

src/client.js (snippet)
const flatfileOptions = {
  publishableKey,
  workbook,
  listener,
  sidebarConfig: {
    showSidebar: false,
  },
  themeConfig: {
    root: {
      primaryColor: "red",
      textColor: "white",
      logo: "https://images.ctfassets.net/hjneo4qi4goj/gL6Blz3kTPdZXWknuIDVx/7bb7c73d93b111ed542d2ed426b42fd5/flatfile.svg",
    },
  },
  // Additional props...
};

7. Set the destination

Finally, let's get the data out of our system and to your destination.

  1. Update your listener.js with this simple submit action.

Once you add this code, when the submit button is clicked, this will be the place you can egress your data. Learn more about Egress Out

src/simple.js
import api from "@flatfile/api";
import { FlatfileListener } from "@flatfile/listener";
import { recordHook } from "@flatfile/plugin-record-hook";

export const listener = FlatfileListener.create((listener) => {
  listener.on("**", (event) => {
    console.log("Event =>", event.topic);
  });

  listener.use(
    recordHook("contacts", (record) => {
      const firstName = record.get("firstName");
      console.log({ firstName });
      record.set("lastName", "Rock");
      return record;
    })
  );

  listener.on(
    "job:ready",
    { job: "workbook:submitActionFg" },
    async ({ context: { jobId } }) => {
      try {
        await api.jobs.ack(jobId, {
          info: "Getting started.",
          // "progress" value must be a whole integer
          progress: 10,
        });

        // Make changes after cells in a Sheet have been updated
        console.log("Make changes here when an action is clicked");

        await api.jobs.complete(jobId, {
          outcome: {
            acknowledge: true,
            message: "This is now complete.",
            next: {
              type: "wait",
            },
          },
        });
      } catch (error) {
        console.error("Error:", error.stack);

        await api.jobs.fail(jobId, {
          outcome: {
            message: "This job encountered an error.",
          },
        });
      }
    }
  );
});

8. Customize

You can stop here or you can view our full reference to see all the ways you can customize your importer.

Example Project

Find this Javascript example project in the Flatfile GitHub repository.