Overview
When embedding Flatfile in React applications, it’s important to understand the proper authentication flow for making API requests. ThepublishableKey is designed exclusively for initializing the FlatfileProvider component, while the accessToken should be used for all subsequent API requests.
Security Best Practice
ThepublishableKey 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 theuseFlatfileInternal 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 theaccessToken:
Complete Example
Here’s a complete example showing how to set up authentication and make API requests:Common API Operations
Once you have theaccessToken, 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 accesssessionSpace.id before the space is created.
Solution: Check both accessToken and sessionSpace:
Key Differences
Summary
Three key steps for secure API requests:- Use
publishableKeyonly forFlatfileProviderinitialization - Access
accessTokenviauseFlatfileInternalhook - Initialize
FlatfileClientwith theaccessTokenfor all API requests
Next Steps
- API Reference - Complete API documentation
- Advanced Configuration - Authentication options
- Server Setup - Backend integration patterns

