Server-side implementation guide for reusing existing spaces
To reuse existing spaces with embedded Flatfile, you need a server-side component that retrieves space access tokens using your secret key. This guide shows you how to set up the server-side pattern correctly.
# .envFLATFILE_API_KEY=sk_1234567890abcdef # Your secret keySPACE_ID=us_sp_abc123def456 # Space ID to reuseBASE_URL=http://localhost:3000 # Your application URL
Here’s a Node.js/Express server that retrieves space access tokens:
Copy
Ask AI
// server.jsimport express from "express";import cors from "cors";import { FlatfileClient } from "@flatfile/api";import dotenv from "dotenv";dotenv.config();const app = express();const PORT = process.env.PORT || 3001;// Initialize Flatfile API with secret keyconst flatfile = new FlatfileClient({ token: process.env.FLATFILE_API_KEY, // Secret key});// Enable CORS for your frontendapp.use( cors({ origin: process.env.BASE_URL || "http://localhost:3000", }));app.use(express.json());// Endpoint to retrieve space with access tokenapp.get("/api/spaces/:spaceId", async (req, res) => { try { const { spaceId } = req.params; // Retrieve space using secret key const space = await flatfile.spaces.get(spaceId); // Return space data including access token res.json({ success: true, data: space.data, // Contains both id and accessToken }); } catch (error) { console.error("Error retrieving space:", error); res.status(500).json({ success: false, error: "Failed to retrieve space", }); }});// Health check endpointapp.get("/health", (req, res) => { res.json({ status: "OK" });});app.listen(PORT, () => { console.log(`Server running on port ${PORT}`);});
// ✅ Good - server-side onlyconst flatfile = new FlatfileClient({ token: process.env.FLATFILE_API_KEY, // Secret key on server});// ❌ Bad - never do this in client codeconst flatfile = new FlatfileClient({ token: "sk_1234567890abcdef", // Secret key exposed});