Node.js

Start integrating any APIs with the Bearer clients for Node.js and Express

Installing and initializing

Node.js
Express.js
npm install @bearer/node
npm install @bearer/node
# For WebHooks
npm install @bearer/express
Node.js
Express.js
// Require the Bearer client for NodeJS
const bearer = require('@bearer/node')(process.env.BEARER_SECRET_KEY)

Replace the BEARER_SECRET_KEY with your Secret Key that can be found on your Developer Keys page.

// Require the Bearer client for NodeJS
const bearer = require('@bearer/node')(process.env.BEARER_SECRET_KEY)
// Initialize Webhook endpoint
import bearerWebhooks from '@bearer/express'
const EncryptionKey = process.env.BEARER_ENCRYPTION_KEY

Replace the BEARER_SECRET_KEY and BEARER_ENCRYPTION_KEY respectively with your Secret Key and Encryption Key that can be found on your Developer Keys page.

Calling APIs

Once you've added an API through the Bearer dashboard, you can make request to it as follow:

// GET request to the GitHub API
bearer
.integration('github')
.get('/repositories', { query: { since: 364 } })
.then(({ data }) => { console.log(data) });

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

To pass parameters, construct your request as follow:

bearer.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 bearer.integration('github')
.get('/repositories')

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

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 on your frontend 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)
bearer.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 your frontend 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)
bearer.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

The Node.js client has a 5 seconds timeout per default. After that period of time, the HTTP connection will be closed by the client.

import bearer from '@bearer/node'
// Set the timeout to 10 seconds for each api
const client = bearer(
process.env.BEARER_SECRET_KEY,
{ httpClientSettings: { timeout: 10 * 1000 } }
)
// set the timeout to 1 second for integration myApi
const myApi = client.integration(
'INTEGRATION_ID',
{ httpClientSettings: { timeout: 1000 } }
)

You can increase the timeout up to 30 seconds, but not more, as it's the limit of our servers.

Tracking requests

The Bearer Node.js client allows you to set a correlationId to make logs grouping easier. This can be done by using the special Bearer-Correlation-Id header.

// Set the correlation id using `Bearer-Correlation-Id` header
github.get('/user/repos', {
headers: { "Bearer-Correlation-Id": "your-correlation-id"
})

On the Bearer dashboard, you can then filter the logs using your-correlation-id.

Receiving Webhooks

Bearer provides a middleware for Express, to handle webhooks easily in your Express application.

Express.js
const webhookHandlers = {
['github']: req =>
new Promise(() => {
// you logic goes here
if (something) resolve()
else {
reject()
}
})
}
app.use('/bearer/webhooks', bearerWebhooks(webhookHandlers, { token: EncryptionKey }))

Not using Express in your app? Get in touch with the team in the Slack community to see how we can help you.

Client reference

This page contains the most common use case for the Bearer API client in Node.js. If you are trying to achieve something not listed here, have a look at the full client reference on the 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.