table of contents Table of contents

Constructs Reference

Project

A Project defines core settings and defaults for the CLI and other constructs like Checks. In many cases, you can just use set defaults for your Checks in the checks property and override them occasionally at the Check or CheckGroup level.

import { defineConfig } from 'checkly'
import { Frequency } from 'checkly/constructs'

export default defineConfig({
  projectName: 'Website Monitoring',
  logicalId: 'website-monitoring-1',
  repoUrl: 'https://github.com/acme/website',
  checks: {
    activated: true,
    muted: false,
    runtimeId: '2022.10',
    frequency: Frequency.EVERY_5M,
    locations: ['us-east-1', 'eu-west-1'],
    tags: ['website', 'api'],
    checkMatch: '**/__checks__/*.check.ts',
    ignoreDirectoriesMatch: [],
    browserChecks: {
      frequency: Frequency.EVERY_10M,
      testMatch: '**/__checks__/*.spec.ts',
    },
  },
  cli: {
    runLocation: 'eu-west-1',
    privateRunLocation: 'private-dc1'
  }
})
  • projectName: A friendly name for your Project.

  • logicalId: A unique identifier for this Project. Like all logical ID’s, this should be stable.

  • repoUrl: An optional URL to a Git repository.

  • checks: Top-level defaults for all Checks in this Project. If not overridden at the Check or CheckGroup level, these settings apply to your Checks. Takes all Check properties

    • checkMatch: A glob pattern where the CLI should look for files containing Check constructs. For more info check the dedicated docs on checkMatch and testMatch
    • ignoreDirectoriesMatch: An array of glob patterns which directories should be ignored by the checkMatch property.
    • browserChecks: Top-level defaults specifically for Browser Checks generated by a glob match pattern. All Check properties are valid here.
  • cli: Defaults for CLI commands.

    • runLocation: The default run location when running npx checkly test.
    • privateRunLocation: The default private run location when running npx checkly test.

Check

The CLI currently supports two Check types: API Checks and Browser Checks. All checks share the following common properties derived from the abstract class Check.

  • name: A friendly name for your Check.
  • frequency: How often to run your Check in minutes, i.e. Frequency.EVERY_1H for every hour.
  • locations: An array of location codes where to run your Checks, i.e. ['us-east-1', 'eu-west-1'].
  • privateLocations: an array of Private Locations slugs, i.e. ['datacenter-east-1'].
  • activated: A boolean value if your Check is activated or not.
  • muted: A boolean value if alert notifications from your Check are muted, i.e. not sent out.
  • group: The CheckGroup object that this check is part of.
  • alertChannels: An array of AlertChannel objects to which to send alert notifications.
  • doubleCheck: A boolean value if Checkly should double check on failure.
  • tags: An array of tags to help you organize your Checks, i.e. ['product', 'api']
  • runtimeId: The ID of which runtime to use for this Check.
  • testOnly: A boolean determining if the Check is available only when test runs and not included when deploy is executed.

Note that most properties have sane default values and do not need to be specified.

ApiCheck

API Checks are a good fit for monitoring typical HTTP based endpoints like REST APIs and GraphQL APIs, but can also be used for form encoded payloads. The example below shows the following:

  • It defines the basic Check properties like name, activated etc.
  • It defines the HTTP method POST, url and the body
  • It sets an extra header in the headers array.
  • It sets an extra parameter in the queryParameters array, although you could add that to the URL directly too.
  • It defines an array of assertions using the AssertionBuilder to assert that:
    • the HTTP response status is 200
    • the JSON response body has a property called name by using the JSON path expression $.name
    • the strict-transport-security response header’s max-age property has a value greater than 100000.
  • It runs a setup script and teardown script, which are just TypeScript files referenced from the same directory.

The file hierarchy looks as follows:

├── __checks__
│   ├── hello-api.check.ts
│   ├── setup.ts
│   ├── teardown.ts
// hello-api.check.ts

import { ApiCheck, AssertionBuilder } from 'checkly/constructs'
import * as path from 'path'

new ApiCheck('hello-api-1', {
  name: 'Hello API',
  activated: true,
  setupScript: {
      entrypoint: path.join(__dirname, 'setup.ts') 
  },
  tearDownScript: {
    entrypoint: path.join(__dirname, 'teardown.ts')     
  },
  maxResponseTime: 10000,
  degradedResponseTime: 5000,
  request: {
    method: 'POST',
    url: 'https://httpbin.org/post',
    body: JSON.stringify({
      name: 'checkly'
    }),
    skipSSL: false,
    followRedirects: true,
    headers: [
      {
        key: 'X-My-Header',
        value: 'My custom header value'
      }
    ],
    queryParameters: [
      {
        key: 'myParam',
        value: 'true'
      }
    ],
    assertions: [
        AssertionBuilder.statusCode().equals(200),
        AssertionBuilder.jsonBody('$.name').notEmpty(),
        AssertionBuilder.headers('strict-transport-security', 'max-age=(\\d+)').greaterThan(10000),
    ]
  }
})
  • setupScript: An object with either an entrypoint property that points to a .js|ts file, or a content property with raw JavaScript / TypeScript as a string. This runs before the API check is executed. Check our docs on how to use setup and teardown scripts.
  • tearDownScript: An object with either an entrypoint property that points to a .js|ts file, or a content property with raw JavaScript / TypeScript as a string. This runs after the API check is executed. Check our docs on how to use setup and teardown scripts.
  • maxResponseTime: The response time in milliseconds where a check should be considered failing.
  • degradedResponseTime: The response time in milliseconds where a check should be considered degraded.
  • request: An object of the Request type. See the Request reference.

Request

The request object is a mandatory part of an API check.

  • url: A string for the target URL.
  • method: The HTTP method as a string, i.e. GET | POST | PUT | PATCH | HEAD | DELETE | OPTIONS
  • body: A string for HTTP request body.
  • bodyType: A string indicating the type of body. Options are JSON | FORM | RAW | GRAPHQL | NONE. This property is mostly for rendering the body type in the web UI and not needed in most cases using the CLI.
  • headers: An array of { key: 'X-My-Header', value: 123 } objects to define HTTP headers.
  • queryParameters: An array of { key: 'my-param', value: 123 } objects to define query parameters.
  • followRedirects: A boolean indicating automatic following of any 30x redirects.
  • skipSSL: A boolean indicating whether invalid or self-signed SSL certificates should be validated.
  • basicAuth: An object of the shape { username: 'admin', password: 'admin' } to set basic auth credentials.
  • assertions: An array of assertions to validate status codes, response bodies and much more. See the AssertionBuilder reference.

AssertionBuilder

To define assertions for the request of an ApiCheck you should use the AssertionBuilder. The AssertionBuilder provides a fluent API for the otherwise slightly cryptic JSON object that the CLI passes to the Checkly API. Here are some examples:

  • Asserting an HTTP status code.
AssertionBuilder.statusCode().equals(200)
// renders to a JSON string
"{ source: 'STATUS_CODE', regex: '', property: '', comparison: 'EQUALS', target: '200' }"
AssertionBuilder.jsonBody('$.data').greaterThan(2000),
// renders to a JSON string
"{ source: 'JSON_BODY', regex: '', property: '$.data', comparison: 'GREATER_THAN', target: '2000' }"
  • Asserting the value of a part of an HTTP response header. Note that you can pass in a regex as the second argument.
AssertionBuilder.headers('strict-transport-security', 'max-age=(\\d+)').greaterThan(10000),
// renders to a JSON string
"{ source: 'HEADERS', regex: 'max-age=(\d+)', property: 'strict-transport-security', comparison: 'GREATER_THAN', target: '100000' }"

The AssertionBuilder defines the following sources as an entry to building an assertion.

  • statusCode(): Assert the HTTP status code for the HTTP request, e.g. 200 or 404.
  • jsonBody(property?): Assert the JSON response body. Accepts a JSON path expression as the property argument.
  • textBody(): Assert the body as raw text.
  • headers(propery?, regex?): Assert a set of response headers, takes the header name as the property argument and a regex to tease out a string from the header value.
  • responseTime(): Assert the total response time of the HTTP request.

Read more about assertions in our docs on API check assertions.

BrowserCheck

Browser Checks are based on @playwright/test. You can just write .spec.js|ts files with test cases and the Checkly CLI will pick them up and apply some default settings like a name, run locations and run frequency to turn them into synthetic monitoring Checks.

However, you can override these global settings and configure individual Browser Checks just like all other built-in Check types. The most important thing is to set the code.entrypoint property and point it to your Playwright .spec.js|ts file. This property supports relative and absolute paths.

import { BrowserCheck } from 'checkly/constructs'
import * as path from 'path'

new BrowserCheck('browser-check-1', {
  name: 'Browser check #1',
  frequency: Frequency.EVERY_10M,
  locations: ['us-east-1', 'eu-west-1'],
  code: {
    entrypoint: path.join(__dirname, 'home.spec.js')
  }
})
  • code: an object with either an entrypoint property that points to .spec.js|ts file, or a content property with raw JavaScript / TypeScript as a string.

CheckGroup

You can explicitly organize Checks in Check Groups.

This brings the following benefits:

  1. Your Checks are organized in a folder in the Checkly web UI.
  2. You can trigger all Checks in a group from the web UI and via a command line trigger.
  3. You can manage group-level configuration like the runtime, activated & muted-state, tags and alert channels that trickle down to all the Checks in the group.

Note: you will notice that managing shared configuration between Checks is very easy just using JS/TS. You might not need Check Groups for that purpose.

Adding Checks to a Check Group

You can add a Check to a group in two ways.

  1. By passing the CheckGroup object for the group property of a Check.
  2. For Browser Checks, we allow you to use the testMatch glob pattern to include any .spec.js|ts file, without having to create a BrowserCheck construct. This works the same ast the testMatch glob at the Project level.
import { CheckGroup, ApiCheck, Frequency } from 'checkly/constructs'

const group = new CheckGroup('check-group-1', {
  name: 'Group',
  activated: true,
  frequency: Frequency.EVERY_15M,
  locations: ['us-east-1', 'eu-west-1'],
  tags: ['api-group'],
  concurrency: 10,
  browserChecks: {
    frequency: Frequency.EVERY_30M,
    testMatch: '*.spec.js'
  }
})

new ApiCheck('check-group-api-check-1', {
  name: 'API check #1',
  group,
  request: {
    method: 'GET',
    url: 'https://mac-demo-repo.vercel.app/api/hello',
  }
})
  • name: A friendly name for your Check Group.
  • concurrency: A number indicating the amount of concurrent Checks to run when a group is triggered.
  • frequency: How often to run the Checks within the group, i.e. Frequency.EVERY_15M for every fifteen minutes.
  • locations: An array of location codes where to run the Checks in the group, i.e. ['us-east-1', 'eu-west-1'].
  • privateLocations: An array of Private Locations slugs, i.e. ['datacenter-east-1'].
  • alertChannels: An array of AlertChannel objects to which to send alert notifications.
  • activated: A boolean value if all the Checks in the group are activated.
  • muted: A boolean value if alert notifications from the Checks in the group are muted, i.e. not sent out.
  • tags: An array of tags. Group tags trickle down to tags on the individual Checks. i.e. ['product', 'api']
  • runtimeId: The ID of which runtime to use for the Checks in the group.
  • environmentVariables: An array of objects defining variables in the group scope, i.e. [{ key: 'DEBUG', value: 'true' }]
  • localSetupScript: Any JS/TS code as a string to run before each API Check in this group.
  • localTearDownScript: Any JS/TS code as a string to run after each API Check in this group.
  • apiCheckDefaults: A set of defaults for API Checks. This should not be needed. Just compose shared defaults using JS/TS.
  • browserChecks: A set of defaults for Browser Checks. This should not be needed. Just compose shared defaults using JS/TS.

When adding checks to a group using testMatch, the CLI searches for files using the corresponding check file as a base path.

Note that you can configure two different frequency properties for API and Browser checks in a CheckGroup separatelly. The CLI follows a fallback logic using Check->CheckGroup->Project configurations.

AlertChannel

Alert channels let you get alert notifications when a Check fails. Learn more about alerting in our docs All alert channels share a set of common properties to define when / how they should alert derived from the abstract class AlertChannel

  • sendRecovery: A boolean if you want to receive recovery notifications.
  • sendFailure: A boolean if you want to receive failure notifications.
  • sendDegrade: A boolean if you want to receive degraded notifications. These only apply to API Checks.
  • sslExpiry: A boolean if you want to receive a notification when a SSL/TLS certificate expires. This works only for API Checks.
  • sslExpiryThreshold: A number indicating how many days before the certificate expiry date a notification will be triggered.

Alert channels are assigned to Checks and CheckGroups by instantiating a class and adding the resulting object to the alertChannels array.

Note that alert channels are only deployed to your Checkly account when referenced explicitly in the alertChannels property of a Project, CheckGroup or Check.

Using fromId() to reference an existing channel

You can reference an existing alert channel in your Checkly account using the fromId() method on any AlertChannel class. This enables you to share an alert channel resource between different projects living in different code repositories.

export const emailChannel = EmailAlertChannel.fromId(20)

You can fetch the ID for your alert channel from web UI or using our REST API.

email channel id

SMSAlertChannel

Sends SMS notifications to phone number. Make sure to use standard international notation.

import { SmsAlertChannel } from 'checkly/constructs'

const smsChannel = new SmsAlertChannel('sms-channel-1', {
  phoneNumber: '0031061234567890',
})

Learn more about SMS alert channels

EmailAlertChannel

Sends email notifications to an email address. Only accepts one address, do not use multiple addresses separated by a comma.

import { EmailAlertChannel } from 'checkly/constructs'

const emailChannel = new EmailAlertChannel('email-channel-1', {
  address: 'alerts@acme.com',
})

SlackAlertChannel

Sends a Slack message to an incoming Slack webhook address. You can specify the target channel.


import { SlackAlertChannel } from 'checkly/constructs'

const slackChannel = new SlackAlertChannel('slack-channel-1', {
  url: 'https://hooks.slack.com/services/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',
  channel: '#ops'
})

Learn more about Slack alert channels

WebhookAlertChannel

Sends a webhook to any URL. Webhooks are very powerful and have quite some options. Here is an example that send

import { WebhookAlertChannel } from 'checkly/constructs'

const webhookChannel = new WebhookAlertChannel('webhook-channel-1', {
  name: 'Pushover webhook',
  method: 'POST',
  url: 'https://api.pushover.net/1/messages.json',
  template: `{
    "token":"FILL_IN_YOUR_SECRET_TOKEN_FROM_PUSHOVER",
    "user":"FILL_IN_YOUR_USER_FROM_PUSHOVER",
    "title":"{{ALERT_TITLE}}",
    "html":1,
    "priority":2,
    "retry":30,
    "expire":10800,
    "message":"{{ALERT_TYPE}} {{STARTED_AT}} ({{RESPONSE_TIME}}ms) {{RESULT_LINK}}"
  }`
})
  • url: The URL where to send the webhook HTTP request.
  • method: A string, either GET, POST, PUT, PATCH, HEAD or DELETE just like an API Check.
  • template: This is commonly a JSON body. You can use Handlebars-style template variables to add custom data to the template.

Learn more about Webhook alert channels and available variables

OpsgenieAlertChannel

Sends an alert notification to your Opsgenie account.

import { OpsgenieAlertChannel } from 'checkly/constructs'

const opsGenieChannel = new OpsgenieAlertChannel('opsgenie-channel-1', {
  name: 'My Ops Team',
  region: 'EU',
  priority: 'P1',
  apiKey: 'xxxx123abc'
})
  • name: Friendly name to recognise the integration.
  • region: A string representing the Opsgenie location, either EU or US.
  • priority: A string representing the severity level, P1 to P5.
  • apiKey: An API key for your Opsgenie account.

Learn more about Opsgenie alert channels

PagerdutyAlertChannel

Sends an alert notification to a specific service in your Pagerduty account

import { PagerdutyAlertChannel } from 'checkly/constructs'

const pagerdutyChannel = new PagerdutyAlertChannel('pagerduty-channel-1', {
  account: 'ACME',
  serviceName: 'ACME products',
  serviceKey: '872b9b58ff4a9n06d0dl9f20487bbqwew'
})
  • account: The name of your Pagerduty account.
  • serviceName: The name of your service defined in Pagerduty under which the alerts should be nested.
  • serviceKey: The API key created by installing the Checkly integration in Pagerduty. We advise you to install the Pagerduty alert channel first from our UI to grab the serviceKey.

Learn more about Pagerduty alert channels

MaintenanceWindow

Creates a maintenance window that lets you schedule planned maintenance and prevents your checks from running at specific times.

import { MaintenanceWindow } from 'checkly/constructs'

new MaintenanceWindow('maintenance-window-1', {
  name: 'Programmed API maintenance',
  tags: ['production', 'api'],
  startsAt: new Date(),
  endsAt: new Date(new Date().valueOf() + (1 * 60 * 60 * 1000)), // a hour from now
  repeatInterval: 1,
  repeatUnit: 'MONTH',
  repeatEndsAt: new Date(new Date().valueOf() + (2160 * 60 * 60 * 1000)), // ~three months from now
})
  • name: A friendly name for your Maintenance Window.
  • tags: An array of tags. A list of one or more tags that filter which checks are affected by the maintenance window. i.e. ['production', 'api'].
  • startsAt: The start date and time of the maintenance window as an ISO 8601 timestamp "YYYY-MM-DDTHH:mm:ss.sssZ" as returned by new Date().
  • endsAt: The end date and time of the maintenance window as an ISO 8601 timestamp "YYYY-MM-DDTHH:mm:ss.sssZ" as returned by new Date().
  • repeatInterval: The repeat interval of the maintenance window from the first occurrence.
  • repeatUnit: The repeat strategy for the maintenance window. This is mandatory when you specify a repeat interval.
  • repeatEndsAt: The end date and time when the maintenance window should stop repeating as an ISO 8601 timestamp "YYYY-MM-DDTHH:mm:ss.sssZ" as returned by new Date()

Learn more about maintenance windows in our docs

Dashboard

Creates a dashboard allowing you to display checks and their related metrics on a single page.

import * as path from 'path'
import { v4 as uuidv4 } from 'uuid'
import { Dashboard } from 'checkly/constructs'
new Dashboard('acme-dashboard-1', {
  header: 'ACME production',
  description: 'service availability and response times',
  tags: ['prod', 'api'],
  logo: 'https://assets.acme.com/images/acme-logo.png',
  customUrl: `status-test-cli-${uuidv4()}`,
  customCSS: {
    entrypoint: path.join(__dirname, 'dashboard.css'),
  }
})

You can add custom CSS by referencing a CSS file. Note, this is a paid feature.

/* dashboard.css */
.header {
  background: #080808;
  border-bottom-color: #313035;
  font-family: "SF Pro Display",-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen,Ubuntu, Cantarell,"Open Sans","Helvetica Neue",sans-serif;
}

.header .logo a {
  color: #f7f8f8;
}
  • tags: A list of one or more tags that filter what checks will be shown in the dashboard. All checks are included if no tag is specified.
  • customUrl: A subdomain name under “checklyhq.com”. Needs to be unique across all users. This is required if customDomain is not specified.
  • customDomain: A custom user domain, e.g. “status.example.com”. See the docs on updating your DNS and SSL usage. This is required if customUrl is not specified.
  • logo: A URL pointing to an image file that will be used as logo in the dashboard header.
  • favicon: A URL pointing to an image file used as dashboard favicon.
  • link: A URL link to redirect when dashboard logo is clicked on.
  • header: A piece of text displayed at the top of your dashboard.
  • description: A piece of text displayed below the header or title of your dashboard.
  • width: Determines whether to use the full screen (FULL) or focus in the center (960PX). Default: FULL.
  • refreshRate: How often (60, 300 or 600 seconds) to refresh the dashboard in seconds. Default: 60.
  • paginate: Determines of pagination is on or off. Default: true.
  • paginationRate?: How often (30, 60 or 300 seconds) to trigger pagination in seconds. Default: 60.
  • checksPerPage: Number of checks displayed per page, between 1 and 20. Default: 15.
  • useTagsAndOperator: When to use AND (instead OR) operator for tags lookup. Default: false.
  • hideTags: Show or hide the tags on the dashboard. Default: false.
  • enableIncidents: Enable or disable incidents on the dashboard. Default: false. (only paid accounts can enable this feature.)
  • expandChecks: Expand or collapse checks on the dashboard. Default: false.
  • showHeader: Show or hide header and description on the dashboard. Default: true.
  • customCSS: Custom CSS to be applied to the dashboard. You can specify CSS code or an entrypoint to a file including the CSS code to use
  • isPrivate: Determines if the dashboard is public or private. Default: false. (only paid accounts can enable this feature.)
  • showP95: Show or hide the P95 stats on the dashboard. Default: true.
  • showP99: Show or hide the P99 stats on the dashboard. Default: true.

Learn more about dashbaords in our docs

PrivateLocation

Creates a Private Location, so you can deploy one or more Checkly Agents on-prem, in a VPC or any segregated network.

// private-location.check.ts
import { PrivateLocation } from 'checkly/constructs'

export const myPrivateLocation = new PrivateLocation('private-location-1', {
  name: 'My private location',
  icon: 'squirrel',
  slugName: `my-private-location`
})

Use the new private location in a Check:

import * as path from 'path'
import { ApiCheck, AssertionBuilder } from 'checkly/constructs'
import { myPrivateLocation } from './private-location.check'

new ApiCheck('local-api-1', {
  name: 'Local API',
  activated: true,
  maxResponseTime: 10000,
  degradedResponseTime: 5000,
  privateLocations: [ myPrivateLocation ],
  request: {
    method: 'POST',
    url: 'https://my-local-domain:5000/post',
    body: JSON.stringify({
      name: 'checkly'
    }),
    skipSSL: true,
    followRedirects: true,
    assertions: [
        AssertionBuilder.statusCode().equals(200),
    ]
  }
})
Note that the privateLocations property on any Check construct directly accepts PrivateLocation instances if the instance is created within the scope of the CLI project. If you want to reference a Private Location created in a different project or created via the Web UI, you can pass in the slugName string.
  • name: A friendly name for your private location.
  • slugName: A valid unique slug name.
  • icon: An icon to distinguish the location in our UI. You can pick any Octicons name.
  • proxyUrl: Define a proxy for outgoing API check HTTP calls from your private location.

Learn more about private locations in our docs


You can contribute to this documentation by editing this page on Github