Reuse a Space when users might need to wait or can’t finish in one go. It’s great for keeping work context and letting users continue where they left off until the task is done.

Before you begin

To reuse an existing Space, we’ll update our files to pass in a Space Id instead of a publishableKey. We’ll then make a server-side request using our secretKey to get the Space and its access token.

Get your keys

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

Note: Unlike the Publishable Key, the Secret Key shouldn’t be passed through the browser as it will have full access. This is why we are showing this example in a server-side call.

Check for proper guestAuthentication

You can skip this step if you haven't created a custom Environment in your Account.

The Space you'll create must have guestAuthentication configured with shared_link as an option. This is inherited from the Environment you're working in, and more info can be found in your Developer Settings page in the platform.

shared_link comes standard on all out-of-the-box Environments (develop / production) so you shouldn't have to do anything unless you have created a custom Environment.

Prepare your project

Install packages

Make a new directory.

mkdir reuse-example-flatfile-js-embed

Go into that directory.

cd reuse-example-flatfile-js-embed

Follow prompts from the init command.

npm init

Install packages.

npm i @flatfile/javascript @flatfile/listener @flatfile/plugin-record-hook @flatfile/api cors dotenv express 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
   └── server.mjs
├── .env
├── 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 “style.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, and the server.mjs file, which sets up a Node.js server using Express that listens for incoming requests and communicates with the Flatfile API to retrieve data about a specified Space.

Update your .env

Update your .env. FLATFILE_API_KEY is your Secret Key and SPACE_ID is the Space you want to open in the importer. This is can be found on your Dashboard where it lists your Spaces. You shouldn’t need to update the BASE_URL.

BASE_URL=https://platform.flatfile.com/api
FLATFILE_API_KEY=sk_1234
SPACE_ID=us_sp_1234

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. Create a local server

This code sets up a Node.js server using Express that listens for incoming requests, enables CORS (Cross-Origin Resource Sharing), and communicates with the Flatfile API to retrieve data about a specified Space based on the provided environment variables.

src/server.mjs
import dotenv from 'dotenv';
import express from 'express';
import { FlatfileClient } from '@flatfile/api';
import cors from 'cors'; // Import the cors module

dotenv.config();

const app = express();
const port = 8080;

console.log(process.env.SPACE_ID);
console.log(process.env.FLATFILE_API_KEY);

const flatfile = new FlatfileClient({
  token: process.env.FLATFILE_API_KEY,
  environment: process.env.BASE_URL + '/v1',
});

// Enable CORS middleware
app.use(cors());

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

app.get('/space', async (req, res) => {
  try {
    const space = await flatfile.spaces.get(process.env.SPACE_ID);
    res.json(space);
  } catch (error) {
    console.error('Error retrieving space:', error);
    res.status(500).json({ error: 'Failed to retrieve space' });
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

3. Start your server

Now, start your server by heading to terminal and running the following command. To see that it’s running, visit: https://localhost:8080 (or the port it is running on) and you should see a page that says “Hello, World”.

npx node src/server.mjs

4. Initialize Flatfile

In your client.js, at minimum, you’ll need to get and pass the space info. This code opens an existing Space in a modal by making a request to your server endpoint and initializing the Flatfile data import with specified options based on the server’s response.

src/client.js
import { initializeFlatfile } from '@flatfile/javascript';
const server_url = 'http://localhost:8080';

//open existing space in modal
window.openFlatfile = () => {
  fetch(server_url + '/space') // Make a request to the server endpoint
    .then((response) => response.json())
    .then((space) => {
      const flatfileOptions = {
        space: {
          id: space && space.data && space.data.id,
          accessToken: space && space.data && space.data.accessToken,
        },
        sidebarConfig: {
          showSidebar: false,
        },
        // Additional props...
      };
      initializeFlatfile(flatfileOptions);
    })
    .catch((error) => {
      console.error('Error retrieving space in client:', error);
    });
};

5. Start your client

Now, start your front end by heading to terminal, opening a new tab, 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 your Space loads. That’s it!

npx parcel public/index.html

6. 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.