JavaScript

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

Installing & initializing

JavaScript
// With a NPM
npm install @bearer/js
// Without NPM
<script src="https://cdn.jsdelivr.net/npm/@bearer/js/lib/bearer.production.min.js"></script>
JavaScript
// With NPM
import bearer from '@bearer/js'
class MyApp {
componentDidMount() {
bearer('BEARER_CLIENT_ID')
}
}
// Without NPM
<script>
const bearerClient = bearer('BEARER_CLIENT_ID')
</script>

Replace the BEARER_CLIENT_ID with your Client ID that can be found on your Developer Keys page.

Calling APIs

JavaScript
const github = bearerClient.integration("github");
const authId = "Generate it with the Connect button"
// GET request with OAuth
github
.auth(authId)
.get("/repositories", { query: { since: 364 } })
.then(({ data }) => { console.log(data) });
// POST Call with OAuth
github
.auth(authId)
.post('/user/repos', { body: { name: 'Just setting up my Bearer.sh' } })
.then(({ data }) => { console.log(data) });
// GET call with a custom header
github
.auth(authId)
.get('/repositories', { headers: { accept: "application/json" }, query: { since: 364 } })
.then(({ data }) => { console.log(data) });

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

We strongly recommend doing it only for OAuth based API.

Adding a Connect button (OAuth)

JavaScript
bearerClient
.connect('github')
.then(data => {
// user has connected himself to the OAuth provider and you now have access to the authId
console.log(data.authId)
})
.catch(() => {
// user canceled the authentication
})

You can pass your own auth-id within options parameters as:

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

Adding a Setup component (user's credential)

By default, you are able to provide your API credentials in the Settings page of the integration.

If you need to ask your users to provide their own, you can easily create a Setup Component on your app.

When users provide their credentials, Bearer will store them and provide in exchange a Setup Id that will then be needed to query the API.

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

JavaScript
<script src="https://cdn.jsdelivr.net/npm/@bearer/js/lib/bearer.production.min.js"></script>
<script>
const bearerClient = bearer('BEARER_CLIENT_ID')
function submitHandler(e) {
bearerClient
.invoke('INTEGRATION_UUID', 'bearer-setup-save', {
setup: {
apiKey: document.querySelector('form').elements[0].value,
type: 'apikey'
}
})
.then(console.log)
.catch(console.error)
return false
}
</script>
<form action="#">
<input type="string" name="apiKey" />
<button type="submit" onclick="submitHandler()">Save</button>
</form>

Check out the source of the JavaScript client.