Skip to main content

JavaScript Quickstart

Developer Key

A rate-limited API developer key can be provisioned from the Sapling API dashboard. Developer keys allow for processing of 50,000 characters every 24 hours. Subscribe for production access and usage-based pricing.

Installation​

Install the @saplingai/sapling-js package with npm

npm install @saplingai/sapling-js

or yarn:

yarn add @saplingai/sapling-js

Fullstack Quickstart​

Here's an example of a basic React App using the Sapling JavaScript observer on the frontend and Sapling backend client for securely managing your API key.

1. Initialize a NodeJS React app​

Run these commands to create a basic React.js app scaffolding and install the necessary npm packages.

cd <project-folder>
npm init -y
npm install express axios cors --save
sudo npm install -g create-react-app
npx create-react-app client
cd client && npm install @saplingai/sapling-js --save
cd ..

2. Setup server-side code​

Create a file outside the client folder called server.js and paste in the following code. This will set up a basic server that will render your React app.

/<project-folder>/server.js
const express = require('express');
const path = require('path');
const cors = require('cors');
const axios = require('axios');

const app = express();
app.use(cors())
app.use(express.json());

app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'));
});

// PLACEHOLDER FOR SAPLING ENDPOINT

// You can change default port but make sure to change for frontend `endpointHostname` as well
const port = process.env.PORT || 5000;
app.listen(port);

console.log('App is listening on port ' + port);

3. Run your app​

In one terminal, run the following code to run the React client code. This will also automatically watch App.js for changes.

cd <project-folder>/client
npm run start

Open a new terminal,

cd <project-folder>
node server.js

The app should now be up and running - open http://localhost:3000 in your browser.

4. Set up a Sapling observer​

Open App.js and replace its contents with the following code

/<project-folder>/client/src/App.js
import './App.css';

import { useEffect } from 'react';
import { Sapling } from "@saplingai/sapling-js/observer";

function App() {
useEffect(() => {
Sapling.init({
endpointHostname: 'http://127.0.0.1:5000',
saplingPathPrefix: '/sapling',
});

const editor = document.getElementById('editor');
Sapling.observe(editor);
});

return (
<div
id="editor"
sapling-ignore="true"
contentEditable="true"
style={{
margin: '40px auto',
padding: '10px',
border: '2px solid black',
width: '500px',
height: '200px'
}}>
Lets get started!
</div>
);
}

export default App;

5. Set up /sapling endpoint​

Open server.js and replace the // PLACEHOLDER FOR SAPLING ENDPOINT with the following endpoint code

/<project-folder>/server.js

const SAPLING_API_URL = 'https://api.sapling.ai';
const API_KEY = '<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));
});
})
caution

Remember to replace your-api-key with the API key from https://sapling.ai/api_settings

Restart the server

cd <project-folder>
node server.js

6. Test it out!​

That's it! Go to http://localhost:3000 and you'll notice a grammatical mistake already highlighted. Simply hover over it and accept the change!

Frontend-Only Quickstart​

If you only need a frontend and will be using your own backend, here's an example of a minimal React App using the Sapling JavaScript observer.

caution

Do not serve a page like this publicly, as it exposes the API key.

  • During development, you can pass in the API key and use Sapling's endpoints by setting mode: 'dev' in the init function.
  • However, for production, do not pass the API key in JavaScript. Instead, include the API key in your backend and call Sapling's endpoints from the backend. This is the default setting with mode: 'prod'.
import { useEffect } from 'react';
import { Sapling } from "@saplingai/sapling-js/observer";


function App() {
useEffect(() => {
Sapling.init({
key: '<api-key>',
endpointHostname: 'https://api.sapling.ai',
editPathname: '/api/v1/edits',
statusBadge: true,
mode: 'dev',
});

const editor = document.getElementById('editor');
Sapling.observe(editor);
});

return (
<div id="editor" sapling-ignore="true" contentEditable="true">
Lets get started!
</div>
);
}

Backend-Only Quickstart​

If you already have a frontend and will only be running a Node backend, here's an example of a minimal Node script using the Sapling JavaScript client.

import { Client } from "@saplingai/sapling-js/client";

const apiKey = '<api-key>';
const client = new Client(apiKey);
client
.edits('Lets get started!')
.then(function (response) {
console.log(response.data);
})

AI Detection​

In the Browser​

Add a button that runs a one-time check on the element you pass to Sapling.observe. It shows an overall score and highlights the sentences flagged as AI-generated.

const checkAI = () => {
const editor = document.getElementById('editor');
Sapling.checkOnce(editor, { aiDetect: true });
};

// In your component's JSX:
<button onClick={checkAI}>Check AI</button>

The AI Detect JavaScript Quickstart has a complete example.

From a Node Backend​

Use aidetect to score how likely a piece of text is to be AI-generated. We recommend at least 300 characters of text.

import { Client } from "@saplingai/sapling-js/client";

const apiKey = '<api-key>';
const client = new Client(apiKey);

const text = 'Phone chargers are essential accessories that have become an integral part of modern life. These devices are designed to replenish the battery life of our smartphones and other electronic gadgets, enabling us to stay connected and productive throughout the day. With advancements in technology, phone chargers have evolved significantly, offering various types such as wired, wireless, fast-charging, and portable chargers. The convenience and versatility of phone chargers have revolutionized the way we use our devices, ensuring we can always stay powered up and connected in our fast-paced, digital world.';

client
.aidetect(text)
.then(function (response) {
console.log(response.data);
})

The result is of this form, with text and sentence_scores covering all of your input. The response also includes token-level scores, omitted here:

{
"score": 0.98,
"ai_fraction": 1.0,
"verdict": "ai",
"segments": [
{ "start": 0, "end": 90, "score": 0.98 }
],
"low_confidence": false,
"low_confidence_reasons": [],
"sentence_scores": [
{
"sentence": "Phone chargers are essential accessories that have become an integral part of modern life.",
"score": 0.98,
"start": 0,
"end": 90
}
],
"text": "Phone chargers are essential accessories that have become an integral part of modern life.",
"version": "..."
}
  • score rates the whole text from 0 to 1, where a value closer to 1 means more confidence that it's AI-generated.
  • ai_fraction is the share of the text in sentences scoring 0.5 or above, which flags documents that are only partly AI-written.
  • verdict sums both up as human, mixed or ai. It's omitted if the text couldn't be scored.
  • segments and sentence_scores show where in the text the result comes from.
  • low_confidence is true for inputs with a higher false-positive rate, such as text under 500 characters. Show those results hedged rather than as a bare score.

All AI detectors have false positives and false negatives, so treat the result as a signal to review rather than as proof.

To score a document or a web page instead of a string, use fileAidetect or urlAidetect:

import { readFileSync } from 'node:fs';

const fromFile = await client.fileAidetect(readFileSync('essay.pdf'), { filename: 'essay.pdf' });
const fromUrl = await client.urlAidetect('https://example.com/blog/post');

More detail on the response and all of the options can be found in the AI Detector API reference. get_ai_detection.mjs is a complete script.