Securing Access Keys
Keeping your access keys safe in production
When working with Function, it’s crucial to keep your access keys secure, as exposing them can lead to unauthorized use of your services. Depending on the environment you are working in, here are guidelines for securing your access keys.
In the Browser
In browser-based applications, you should never expose your access key directly in your front-end code. Instead, proxy your requests through a backend route that handles the access key securely. Here’s how you can do it:
Create a Frontend Client
In the browser, the Function client should reference an API route on your backend. For example:
// In your browser code...
const fxn = new Function({ url: "/api" });
Create a Backend Route
On the backend, create an API route that securely handles the access key. For example, if you’re using the Next.js App Router, you can define a route like this:
export async function POST (request: NextRequest) {
// Create an authenticated client
const fxn = new Function({ accessKey: process.env.FXN_ACCESS_KEY });
// Make a prediction
const body = await request.json();
const prediction = await fxn.predictions.create(body);
// Respond with prediction
return NextResponse.json(prediction);
}
Make sure to not pass in any inputs
when creating a prediction on the backend.
This ensures that the access key is securely stored on your server, while the browser interacts with your backend to make requests.
In Node.js
For Node.js applications, storing your access key in environment variables is a best practice. This keeps the key out of your codebase and secure on your system.
Create a Dotenv File
Create a .env
file in the root of your project and store your access key like this:
# Function
FXN_ACCESS_KEY="..."
When starting your Node process, you can then reference this .env
file:
# Start your Node process and load the `.env` file
# This requires Node 20.6+
$ node app.js --env-file .env
Finally, make sure that your .env
file is never committed to version control by adding it to your .gitignore
:
# Environment variables and secrets
.env
Create a Function Client
The Function client will automatically load the access key from the environment variable when instantiated in your code:
// Create a Function client.
const fxn = new Function();
In Unity
In Unity applications, we strongly recommend following the same approach as in the browser:
// In Unity code...
var fxn = new Function(url: "https://your.company.com/api");
In other cases, simply ensure that your Function settings for your Unity project are not committed to version control:
# Function
ProjectSettings/Function.asset