Skip to main content

Overview

When embedding Flatfile in React applications, it’s important to understand the proper authentication flow for making API requests. The publishableKey is designed exclusively for initializing the FlatfileProvider component, while the accessToken should be used for all subsequent API requests.

Security Best Practice

The publishableKey is restricted to its intended use: initializing the Flatfile embedded experience. For security reasons, it cannot be used to make API requests directly. Instead, use the accessToken that becomes available after the Space is created.

Accessing the Access Token

Use the useFlatfileInternal hook to access the accessToken and sessionSpace after initialization:
The accessToken will be undefined until the space is actually created (after openPortal() is called and the space is initialized). Always check for its availability before making API calls.

Making API Requests

Basic Pattern

Here’s the recommended pattern for making API requests using the accessToken:

Complete Example

Here’s a complete example showing how to set up authentication and make API requests:

Common API Operations

Once you have the accessToken, you can perform various operations:

Handling User Actions

For API calls triggered by user actions, ensure the token is available:

Creating a Custom Hook

For cleaner code, create a custom hook for API access:

Troubleshooting

”accessToken is undefined”

Cause: The space hasn’t been created yet. Solution: Add null checks and wait for the token:

“Cannot read property ‘id’ of undefined”

Cause: Trying to access sessionSpace.id before the space is created. Solution: Check both accessToken and sessionSpace:

Key Differences

Summary

Three key steps for secure API requests:
  1. Use publishableKey only for FlatfileProvider initialization
  2. Access accessToken via useFlatfileInternal hook
  3. Initialize FlatfileClient with the accessToken for all API requests
This pattern ensures your API calls are properly authenticated and scoped to the correct space.

Next Steps