table of contents Table of contents

API setup script examples

Here are some examples on how to address common authentication use cases with setup scripts.

Using Vercel deployment protection? Read this section on how to make this work with Checkly.

Fetch an external token

import { axios } from 'axios'

// use 'await' on an axios HTTP get to fetch a token from a location
const { data } = await axios.get('https://example.com/api/token')

// add the token as a query parameters
request.queryParameters['token'] = data.token
const axios = require('axios')

// use 'await' on an axios HTTP get to fetch a token from a location
const { data } = await axios.get('https://example.com/api/token')

// add the token as a query parameters
request.queryParameters['token'] = data.token

Sign an HMAC request

import CryptoJS from 'crypto-js'
import moment from 'moment'

// get keys stored in environment variables
const privateKey = process.env.PRIVATE_KEY
const publicKey = process.env.PUBLIC_KEY

// collect the fields used in signing the request
const method = request.method
const contentType = 'application/json'
const contentMd5 = ''
const url = request.url
const host = 'localhost:8080'
const uri = url.replace(/^.*\/\/[^\/]+/, '')
const timestamp = moment().toISOString()

// create the signature
const signature = [method, contentMd5, contentType, timestamp].join(',\n')
const encryptedSignature = publicKey + ':' + CryptoJS.HmacSHA1(signature, privateKey).toString(CryptoJS.enc.Base64)

// set or update the results as environment variables, to be used in the HTTP request.
process.env.TIMESTAMP = timestamp
process.env.ENCRYPTED_SIGNATURE = encryptedSignature
process.env.CONTENT_TYPE = contentType
const CryptoJS = require('crypto-js')
const moment = require('moment')

// get keys stored in environment variables
const privateKey = process.env.PRIVATE_KEY
const publicKey = process.env.PUBLIC_KEY

// collect the fields used in signing the request
const method = request.method
const contentType = 'application/json'
const contentMd5 = ''
const url = request.url
const host = 'localhost:8080'
const uri = url.replace(/^.*\/\/[^\/]+/, '')
const timestamp = moment().toISOString()

// create the signature
const signature = [method, contentMd5, contentType, timestamp].join(',\n')
const encryptedSignature = publicKey + ':' + CryptoJS.HmacSHA1(signature, privateKey).toString(CryptoJS.enc.Base64)

// set or update the results as environment variables, to be used in the HTTP request.
process.env.TIMESTAMP = timestamp
process.env.ENCRYPTED_SIGNATURE = encryptedSignature
process.env.CONTENT_TYPE = contentType

Sign an AWS API request

import aws4 from 'aws4'
import axios from 'axios'

// set up AWS request variables
const url = 'https://s3.eu-central-1.amazonaws.com/checkly-private-test/test.txt'
const options = {
    service: 's3',
    region: 'eu-central-1',
    path: '/checkly-private-test/test.txt'
}

// set up AWS credentials
const credentials = {
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    accessKeyId: process.env.AWS_ACCESS_KEY_ID
}

// use the aws4 library to sign the request
const signature = aws4.sign(options, credentials)

// fetch the data and store in an environment variable
const { data } = await axios.get(url, { headers: signature.headers })
process.env.AWS_V4_RESULT = data
const aws4 = require('aws4')
const axios = require('axios').default

// set up AWS request variables
const url = 'https://s3.eu-central-1.amazonaws.com/checkly-private-test/test.txt'
const options = {
  service: 's3',
  region: 'eu-central-1',
  path: '/checkly-private-test/test.txt'
}

// set up AWS credentials
const credentials = {
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  accessKeyId: process.env.AWS_ACCESS_KEY_ID
}

// use the aws4 library to sign the request
const signature = aws4.sign(options, credentials)

// fetch the data and store in an environment variable
const { data } = await axios.get(url, { headers: signature.headers })
process.env.AWS_V4_RESULT = data

Fetch an OAuth2 access token using the client_credentials grant

This example works great for OAuth2 providers like Okta and Auth0 that provide the “client_credentials” grant type.

import axios from 'axios'

// grab the necessary credentials set up earlier in your environment variables.
const { AUDIENCE, CLIENT_SECRET, CLIENT_ID, ISSUER } = process.env;

// fetch an access token
const { data: { access_token } } = await axios.post(`${ISSUER}/oauth/token`,
    {
      grant_type: "client_credentials",
      client_id: `${CLIENT_ID}`,
      client_secret: `${CLIENT_SECRET}`,
      audience: `${AUDIENCE}`,
    },
    {
      headers: { "content-type": "application/x-www-form-urlencoded" }
    }
)

// set the Authorization header
request.headers['Authorization'] = `Bearer ${access_token}`
const axios = require('axios')

// grab the necessary credentials set up earlier in your environment variables.
const { AUDIENCE, CLIENT_SECRET, CLIENT_ID, ISSUER } = process.env;

// fetch an access token
const { data: { access_token } } = await axios.post(`${ISSUER}/oauth/token`,
  {
    grant_type: "client_credentials",
    client_id: `${CLIENT_ID}`,
    client_secret: `${CLIENT_SECRET}`,
    audience: `${AUDIENCE}`,
  },
  {
    headers: { "content-type": "application/x-www-form-urlencoded" }
  }
)

// set the Authorization header
request.headers['Authorization'] = `Bearer ${access_token}`

Fetch an OAuth2 access token using the password grant

This example works great for OAuth2 providers like Okta and Auth0 that provide the “password” grant type. We actually use this one ourselves for monitoring Checkly!

import axios from "axios";

// grab the necessary credentials set up earlier in your environment variables.
const { AUDIENCE, CLIENT_SECRET, CLIENT_ID, ISSUER, USERNAME, PASSWORD, SCOPE } = process.env;

// fetch an access token
const { data: { access_token } } = await axios.post(`${ISSUER}/oauth/token`,
    {
        grant_type: 'password',
        username: `${USERNAME}`,
        password: `${PASSWORD}`,
        audience: `${AUDIENCE}`,
        scope: `${SCOPE}`,
        client_id: `${CLIENT_ID}`,
        client_secret: `${CLIENT_SECRET}`
    },
    {
        headers: { "content-type": "application/x-www-form-urlencoded" }
    }
)

// set the Authorization header
request.headers['Authorization'] = `Bearer ${access_token}`
const axios = require('axios')

// grab the necessary credentials set up earlier in your environment variables.
const { AUDIENCE, CLIENT_SECRET, CLIENT_ID, ISSUER, USERNAME, PASSWORD, SCOPE } = process.env;

// fetch an access token
const { data: { access_token } } = await axios.post(`${ISSUER}/oauth/token`,
    {
      grant_type: 'password',
      username: `${USERNAME}`,
      password: `${PASSWORD}`,
      audience: `${AUDIENCE}`,
      scope: `${SCOPE}`,
      client_id: `${CLIENT_ID}`,
      client_secret: `${CLIENT_SECRET}`
    },
    {
        headers: { "content-type": "application/x-www-form-urlencoded" }
    }
)

// set the Authorization header
request.headers['Authorization'] = `Bearer ${access_token}`

Create a JWT token using the jsonwebtoken library

// we use the jsonwebtoken library as it makes creating JTW's really easy
import jwt from 'jsonwebtoken'

// grab the secret from our environment variables
const secret = process.env.SECRET

// define a helper function to sign the token
const getToken = () => {
    return new Promise((resolve, reject) => {
        jwt.sign({
            expiry: Math.floor(Date.now() / 1000) + (60 * 60), // set the expiry time to 60 minutes
            email: '',
            userId: '',
        }, secret , (err, token) => {
            if(err) return reject(err);
            resolve(token);
        });
    })
}

// create the token
const token = await getToken();

// set the Authorization header
request.headers['Authorization'] = `Bearer ${token}`
// we use the jsonwebtoken library as it makes creating JTW's really easy
const jwt = require('jsonwebtoken');

// grab the secret from our environment variables
const secret = process.env.SECRET

// define a helper function to sign the token
const getToken = () => {
  return new Promise((resolve, reject) => {
    jwt.sign({
      expiry: Math.floor(Date.now() / 1000) + (60 * 60), // set the expiry time to 60 minutes
      email: '',
      userId: '',
    }, secret , (err, token) => {
      if(err) return reject(err);
      resolve(token);
    });
  })
}

// create the token
const token = await getToken();

// set the Authorization header
request.headers['Authorization'] = `Bearer ${token}`

Parse XML/SOAP data

To parse XML and potentially prepare a SOAP API Check, fetch the API data, parse the XML and store the parsed value in an environment variable to make it accessible in an API Check request body.

import axios from 'axios'

// Make an XML request
const { data } = await axios.post(
    "https://www.dataaccess.com/webservicesserver/NumberConversion.wso",
    `<?xml version="1.0" encoding="utf-8"?>
      <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
          <NumberToWords xmlns="http://www.dataaccess.com/webservicesserver/">
            <ubiNum>42</ubiNum>
          </NumberToWords>
        </soap:Body>
    </soap:Envelope>
  `,
    {
        headers: {
            "content-type": "text/xml; charset=utf-8",
        },
    }
)

// Parse the value you're interested in
const regExp = /<m:NumberToWordsResult>(.*?)<\/m:NumberToWordsResult>/g
const result = regExp.exec(data)

if (result.length > 1) {
    // Store it in an environment variable to access it in your API Check request body
    process.env.NUMBER_TO_WORD_RESULT = result[1]
} else {
    throw new Error("Could not parse XML")
}
const axios = require('axios').default

// Make an XML request
const { data } = await axios.post(
  "https://www.dataaccess.com/webservicesserver/NumberConversion.wso",
  `<?xml version="1.0" encoding="utf-8"?>
      <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
          <NumberToWords xmlns="http://www.dataaccess.com/webservicesserver/">
            <ubiNum>42</ubiNum>
          </NumberToWords>
        </soap:Body>
    </soap:Envelope>
  `,
  {
    headers: {
      "content-type": "text/xml; charset=utf-8",
    },
  }
)

// Parse the value you're interested in
const regExp = /<m:NumberToWordsResult>(.*?)<\/m:NumberToWordsResult>/g
const result = regExp.exec(data)

if (result.length > 1) {
  // Store it in an environment variable to access it in your API Check request body
  process.env.NUMBER_TO_WORD_RESULT = result[1]
} else {
  throw new Error("Could not parse XML")
}

Last updated on November 7, 2024. You can contribute to this documentation by editing this page on Github