JavaScript

Take advantage of the Bearer client for JS to call APIs, connect your users to OAuth APIs and save API credentials.

Installing

JavaScript
React
npm install @bearer/js
npm install @bearer/react

Initializing

JavaScript
React
// With NPM
import bearer from '@bearer/js'
const bearerClient = bearer('BEARER_PUBLISHABLE_KEY')
// Without NPM
<script src="https://cdn.jsdelivr.net/npm/@bearer/js/lib/bearer.production.min.js"></script>
<script>const bearerClient = bearer('BEARER_PUBLISHABLE_KEY')</script>
import * as React from "react";
import bearer from "@bearer/js";
const bearerClient = bearer(BEARER_PUBLISHABLE_KEY);

Replace the BEARER_PUBLISHABLE_KEY with your Publishable Key that can be found on your Developer Keys page.

Calling APIs

By default and for security reasons, calling APIs from a client-side context is deactivated. You can enable this option API per API, on the Settings page of the integration.

We strongly recommend doing it only for OAuth based API.

Once you've added an API through the Bearer dashboard and enable client-side API calls, you can make request to it as follow:

JavaScript
React
// GET request to the GitHub API
bearerClient
.integration("github")
.get("/repositories", { query: { since: 364 } })
.then(({ data }) => { console.log(data) });
import * as React from "react";
import bearer from "@bearer/js";
const bearerClient = bearer(BEARER_PUBLISHABLE_KEY);
const github = bearerClient.integration("github");
class Repositories extends React.Component<{ authId: string }, { data: any }> {
constructor(props) {
super(props);
this.state = { data: "" };
}
fetch = () => {
github
.auth(this.props.authId) // Generate it with the connect button
.get("/repositories", {
headers: { accept: "application/json" },
query: { since: 364 }
})
.then(({ data }) => {
this.setState({ data: JSON.stringify(data) });
});
};
componentWillMount() {
this.fetch();
}
render() {
return <pre>{this.state.data}</pre>;
}
}
export default Repositories;

Most common HTTP methods are supported out-of-the-box, including .get() , .post(), .put()and.delete().

To pass parameters, construct your request as follow:

bearerClient.integration('github')
.get('/endpoint', {
query: { 'foo': 'bear'}, // your query parameters as key/value
body: {}, // your body as key/value or string
headers: { 'foo': 'bear' } // your headers as key/value
})

Async / await

Using async/await is supported to improve code readability:

const response = await bearerClient.integration('github')
.get('/repositories')

In that snippet, response will be an Axios response schema as we rely on that library.

Credentials management

By default, all requests will be authenticated using the latest credentials saved into your account for that API. Thus, changing the API credentials in your account will be instantly reflected into your code.

If you want to use custom credentials, for example your customers credentials, first retrieve them with the setup component, then update your code to use the .setup() method as follow:

// GET request to the GitHub API with custom credentials
// (retrieve a setupId with the Bearer setup component)
bearerClient.integration('github')
.setup(setupId)
.get("/repositories", { query: { since: 364 } })
.then(({ data }) => { console.log(data) });

Dealing with OAuth APIs

When the API you want to use rely on OAuth as an authentication method, Bearer will handle the OAuth dance for you.

Just add a connect button to let your users connect to the service. Then update your script to use the .auth() method as follow:

// POST request using an authId (only for OAuth APIs)
// (generate an authId with the Bearer connect button)
bearerClient.integration('github')
.auth(authId) // callback value of the connect button
.post('/user/repos', { body: { name: 'Just setting up my Bearer.sh' } })
.then(({data}) => { console.log('Success:', data) })
.catch(err => { console.log('Error: ', err) })

Request timeout

Each API call performed through Bearer has a 6 seconds timeout. After that period of time, the HTTP connection will be closed by our servers.

Adding a Connect button (OAuth APIs)

The connect button lets you trigger an OAuth dance to connect a user with the API provider every time a user clicks on it. Thus, your application is granted a personal and limited access to a user account. Learn more about the connect button in the FAQ section.

JavaScript
React
bearerClient.connect('github')
.then(data => {
// user has connected himself to the OAuth provider
// and you now have now access to the authId.
console.log(data.authId)
})
.catch(() => {
// user canceled the authentication.
})
import * as React from "react";
import { Bearer, factory } from "@bearer/react";
const { Connect } = factory('github');
const MyConnectComponent = () => {
const onSuccess = ({ authId }) => {
// Use this authId later like bearer.auth(authId).get(..
console.log('AUTH_ID for this user', authId)
}
return (
// Initialize the Bearer provider with your client ID
<Bearer clientId=BEARER_PUBLISHABLE_KEY>
<Connect
onSuccess={onSuccess}
render={({ connect }) => {
return (
<button onClick={connect}>
Connect to Github
</button>
);
}}
/>
</Bearer>
);
};
export default MyConnectComponent;

Protip, you can pass your own authId within the options parameters as follow:

bearerClient.connect('github', {
authId: 'a-secure-non-guessable-auth-id'
})

In case you manage multiple credentials on the same API, you can as well pass setupId within the options of the connect button:

bearerClient.connect('github', {
setupId: 'a-setup-id-retrieved-from-the-setup-component'
})

Adding a Setup component

Most of the time, you will provide your API credentials in the Settings page. But sometimes, you might want to collect the API credentials of your own users.

Here is an example of a Setup Component for an API Key based integration:

JavaScript
React
<!DOCTYPE html>
<form id="bearer-setup-component">
<input type="text" name="apiKey" />
<button type="submit">Save</button>
</form>
<script src="https://cdn.jsdelivr.net/npm/@bearer/js/lib/bearer.production.min.js"></script>
<script>
const integration = 'REPLACE_WITH_THE_INTEGRATION_NAME'
const form = document.getElementById('bearer-setup-component')
// Initialize the Bearer JS client
const bearerClient = bearer(BEARER_PUBLISHABLE_KEY)
// Handle submit event on the form
form.addEventListener('submit', submitHandler)
function submitHandler(e) {
e.preventDefault()
return bearerClient
.invoke(integration, 'bearer-setup-save', {
setup: {
apiKey: form.elements['apiKey'].value,
type: 'apikey'
}
})
.then(console.log)
.catch(console.error)
}
</script>
import * as React from "react"
import { BearerContext } from "@bearer/react/lib/bearer-provider"
const MyComponent = () => {
const [setupId, setSetupId] = React.useState();
const context = useContext(BearerContext);
const handleClick = (e: any) => {
context.bearer
.invoke("INTEGRATION_UUID", "bearer-setup-save", {
setup:{
apiKey: "value",
type: "apikey"
}
})
.then(data => { setSetupId(data.setupId); })
.catch(console.error);
}
return (
<button type="button" onClick={this.handleClick}>Click Me</button>
)
}

Learn more about the setup component in the dedicated FAQ section.

Client reference

This page contains the most common use case for the Bearer API client in JavaScript and React. If your use case is not listed here, dive into the full client reference on its respective README on GitHub:

Each client reference includes details about the functions, classes, return types, arguments and more, supported by tutorials and examples. As well as the source code of the client.