Skip to main content

Frontend Key Management

There are two main ways of authenticating SDK server requests without exposing your API key in public environments:

  1. Proxying requests through your backend
  2. Authentication with a JWT key

1. Proxying Requests

This is a way to use the SDK by adding the private API Key to the API calls from a backend server.

  • Set up a backend endpoint with your API key to request edits.
  • Text from the public page is passed to the backend which adds the API key before proxying onto Sapling servers.

A full working example using React, Webpack and Express can be downloaded here:

Frontend Code (javascript/express-app/src/App.js)

Sapling.init({
endpointHostname: 'http://127.0.0.1:3000', // Set endpoint to your own server
saplingPathPrefix: '/sapling',
});

Backend Code (javascript/express-app/src/server.mjs)

const SAPLING_API_URL = 'https://api.sapling.ai';
const API_KEY = '<private-api-key>';

app.post('/sapling/*', (req, res, next) => {
// remove the '/sapling/' prefix from the request path
let requestPath = req.path.substring(8);
// pass request path along to Sapling
let requestUrl = `${SAPLING_API_URL}${requestPath}`;
// add the API Key
req.body.key = API_KEY;
axios({
url: requestUrl,
data: req.body,
method: 'post',
})
.then(function (response) {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(response.data));
});
})

2. JWT Keys

This is a way to generate a short term JWT token for authentication without exposing your private API Key. You can sign a JWT token with the following claims:

{
"sub": "<public-api-key>",
"exp": <expiration_time>,
}

The expiration time is specified as seconds from Epoch (January 1, 1970 Midnight UTC). The generated JWT token can be passed into the SDK under the key field without exposing the private key. Here are some examples of generating JWT tokens:

const jwt = require('jsonwebtoken');

const current_time = Math.floor(Date.now() / 1000);
const expiration_time = current_time + 864000; // 10 days
const private_key = '<private-api-key>';
const public_key = '<public-api-key>';

const claims = {
'sub': public_key,
'exp': expiration_time,
};

const jwtToken = jwt.sign(claims, private_key, { algorithm: 'HS256' });
console.log(jwtToken);