Scripting GuideExternal Libraries

External Libraries

ReAPI provides comprehensive JavaScript library support for all scripting contexts, allowing you to leverage powerful third-party libraries for data manipulation, validation, HTTP requests, and more.

Library Types

ReAPI supports three types of libraries:

  1. Built-in Libraries - Always available, no configuration needed
  2. Predefined Libraries - Curated collection with one-click installation
  3. Custom Libraries - Load any IIFE/UMD library from a public URL

Built-in Libraries

These libraries are pre-loaded and always available in all script execution environments without any setup or configuration.

Lodash (_)

Purpose: Utility library for data manipulation, array operations, object handling, and functional programming.

Documentation: https://lodash.com/

Version: 4.17.21

Example:

async function beforeRequest() {
  // Array manipulation
  const chunks = _.chunk(["a", "b", "c", "d"], 2);
  // [['a', 'b'], ['c', 'd']]
 
  // Deep clone objects
  const cloned = _.cloneDeep($context.userData);
 
  // Data transformation
  const users = _.map($context.users, (user) => ({
    id: user.id,
    name: _.upperFirst(user.name),
  }));
}

Faker

Purpose: Generate realistic mock data for testing - names, emails, addresses, phone numbers, and more.

Documentation: https://fakerjs.dev/

Version: 9.8.0

Example:

async function generateValue() {
  return {
    email: faker.internet.email(),
    username: faker.internet.userName(),
    password: faker.internet.password(),
    uuid: faker.string.uuid(),
    company: faker.company.name(),
    address: faker.location.streetAddress(),
  };
}

Zod (z)

Purpose: TypeScript-first schema validation library for runtime data validation and type safety.

Documentation: https://zod.dev/

Version: 4.1.12

Example:

async function afterResponse() {
  // Define schema
  const userSchema = z.object({
    id: z.number(),
    email: z.string().email(),
    name: z.string().min(2),
    age: z.number().min(18).optional(),
  });
 
  // Validate response
  try {
    const user = userSchema.parse($response.body);
    $context.validatedUser = user;
  } catch (error) {
    throw new Error(`Validation failed: ${error.message}`);
  }
}

Ky

Purpose: Modern, lightweight HTTP client based on Fetch API with better error handling and retry logic.

Documentation: https://github.com/sindresorhus/ky

Version: 1.7.3

Example:

async function beforeRequest() {
  // Make HTTP requests with automatic retry
  const data = await ky
    .get("https://api.example.com/data", {
      timeout: 5000,
      retry: 3,
      headers: {
        Authorization: `Bearer ${$context.token}`,
      },
    })
    .json();
 
  $context.fetchedData = data;
}

Luxon

Purpose: Modern, powerful date/time library for parsing, formatting, and manipulating dates and times.

Documentation: https://moment.github.io/luxon/

Version: 3.7.2

Example:

async function beforeRequest() {
  const { DateTime } = luxon;
 
  // Current time
  const now = DateTime.now();
 
  // Format dates
  const formatted = now.toFormat("yyyy-MM-dd HH:mm:ss");
 
  // Date arithmetic
  const tomorrow = now.plus({ days: 1 });
  const nextWeek = now.plus({ weeks: 1 });
 
  // Parse and convert
  const parsed = DateTime.fromISO("2024-01-01T12:00:00");
  const unix = parsed.toSeconds();
 
  $request.headers["X-Timestamp"] = now.toISO();
}

Native APIs

These JavaScript built-in APIs are also available:

  • fetch - Native Fetch API for HTTP requests (MDN)
  • Math - Mathematical functions
  • Date - Native date operations
  • JSON - JSON parsing and stringification
  • console - Console logging (use $log for test output)

Predefined Libraries

ReAPI provides a curated collection of popular libraries that you can add to your scripts with one click in the script editor.

💡 Recommendation: Prefer using built-in libraries when possible. For example:

  • Use Luxon (built-in) instead of Moment or DayJS for date/time operations
  • Use Ky (built-in) instead of Axios for HTTP requests
  • Use Zod (built-in) instead of Validator for schema validation

Built-in libraries are pre-loaded, faster, and require no configuration.

CryptoJS

Purpose: Cryptographic operations including encryption, hashing (MD5, SHA256), HMAC signatures, and encoding.

Documentation: https://cryptojs.gitbook.io/docs

Version: 4.2.0

Use Cases:

  • API request signing (HMAC-SHA256)
  • Password hashing
  • Data encryption/decryption
  • Generating secure tokens

Example:

async function beforeRequest() {
  // Generate HMAC signature for API authentication
  const timestamp = Date.now().toString();
  const payload = `${$request.method}${$request.url}${timestamp}`;
 
  const signature = CryptoJS.HmacSHA256(payload, $context.apiSecret).toString();
 
  $request.headers["X-Signature"] = signature;
  $request.headers["X-Timestamp"] = timestamp;
}

DayJS

Purpose: Lightweight date manipulation library, a smaller alternative to Moment.js.

Documentation: https://day.js.org/

Version: 1.11.12

💡 Consider using Luxon (built-in) instead for better performance and modern date/time handling.

Use Cases:

  • Date formatting
  • Date arithmetic
  • Relative time
  • Calendar operations

Example:

async function generateValue() {
  return {
    today: dayjs().format("YYYY-MM-DD"),
    lastWeek: dayjs().subtract(7, "day").format("YYYY-MM-DD"),
    nextMonth: dayjs().add(1, "month").format("YYYY-MM-DD"),
  };
}

Axios

Purpose: Feature-rich HTTP client with interceptors, automatic JSON transformation, and progress tracking.

Documentation: https://axios-http.com/

Version: 1.7.4

💡 Consider using Ky (built-in) instead for modern, lightweight HTTP requests with automatic retry and better error handling.

Use Cases:

  • Complex HTTP requests
  • Request/response interceptors
  • Upload/download progress tracking
  • Concurrent requests

Example:

async function beforeRequest() {
  // Make multiple concurrent requests
  const [users, posts] = await Promise.all([
    axios.get("https://api.example.com/users"),
    axios.get("https://api.example.com/posts"),
  ]);
 
  $context.users = users.data;
  $context.posts = posts.data;
}

Moment

Purpose: Comprehensive date/time library with extensive formatting and timezone support.

Documentation: https://momentjs.com/

Version: 2.30.1

💡 Consider using Luxon (built-in) instead - Luxon is the modern successor to Moment.js, offering better performance and immutability.

Use Cases:

  • Complex date formatting
  • Timezone conversions
  • Date parsing from various formats
  • Calendar calculations

Example:

async function beforeRequest() {
  const dateTime = moment().format("dddd, MMMM Do YYYY, h:mm:ss a");
  $request.headers["X-Request-Time"] = dateTime;
}

Validator

Purpose: String validation and sanitization library for emails, URLs, UUIDs, and more.

Documentation: https://github.com/validatorjs/validator.js

Version: 13.12.0

💡 Consider using Zod (built-in) instead for type-safe schema validation with better TypeScript support and composable validators.

Use Cases:

  • Input validation
  • Data sanitization
  • Format checking
  • Security validation

Example:

async function afterResponse() {
  const email = $response.body.email;
 
  if (!validator.isEmail(email)) {
    throw new Error("Invalid email format");
  }
 
  if (!validator.isUUID($response.body.id)) {
    throw new Error("Invalid UUID format");
  }
}

Turf.js

Purpose: Advanced geospatial analysis and GeoJSON manipulation.

Documentation: https://turfjs.org/

Version: 7.x

Use Cases:

  • Geospatial calculations
  • Distance and area measurements
  • Point-in-polygon checks
  • GeoJSON transformations

Example:

async function afterResponse() {
  const line = turf.lineString([
    [-83, 30],
    [-84, 36],
    [-78, 41],
  ]);
 
  // Calculate point 200 miles along the line
  const along = turf.along(line, 200, { units: "miles" });
 
  $context.calculatedPoint = along;
}

Numeral

Purpose: Number formatting and manipulation for currency, percentages, and custom formats.

Documentation: http://numeraljs.com/

Version: 2.0.6

Use Cases:

  • Currency formatting
  • Number localization
  • Percentage calculations
  • Custom number formats

Example:

async function afterResponse() {
  const amount = $response.body.amount;
 
  const formatted = numeral(amount).format("$0,0.00");
  $context.formattedAmount = formatted;
}

Custom Libraries

You can load any JavaScript library in IIFE or UMD format from a public URL.

Supported Formats

IIFE (Immediately Invoked Function Expression)

var libraryName = (function () {
  /* ... */
})();

UMD (Universal Module Definition)

(function (root, factory) {
  /* ... */
})(this, function () {
  /* ... */
});

ESM (ES Modules) - Not directly supported

export default function () {
  /* ... */
}

Note: For ESM modules, use our ESM Bundler Service to convert them to IIFE format.

How to Add Custom Libraries

In your script configuration, specify the library URL in the libs array:

{
  code: "async function beforeRequest() { /* your code */ }",
  libs: [
    "https://cdn.jsdelivr.net/npm/library-name@version/dist/library.min.js"
  ]
}
  • jsDelivr - Fast, reliable, and well-cached
  • unpkg - NPM package CDN
  • cdnjs - Large library collection

Example: Using a Custom Library

// Script configuration
{
  code: `
    async function beforeRequest() {
      // Use the custom library (assuming it exposes 'customLib')
      const result = customLib.someFunction($context.data)
      $request.headers['X-Custom-Header'] = result
    }
  `,
  libs: [
    "https://cdn.jsdelivr.net/npm/some-library@1.0.0/dist/bundle.min.js"
  ]
}

Finding IIFE/UMD Bundles

Most libraries provide IIFE/UMD builds. Look for:

  • Files named *.min.js, *.umd.js, or *.iife.js
  • Directories named dist/, umd/, or browser/
  • Check the library’s documentation for “browser” or “CDN” usage

Example library structures:

lodash/
  └── lodash.min.js ✅ (IIFE)

axios/
  └── dist/
      └── axios.min.js ✅ (UMD)

moment/
  └── min/
      └── moment.min.js ✅ (UMD)

ESM Bundler Service

For modern JavaScript libraries that only provide ESM (ES Modules) format, ReAPI offers a free bundler service that converts ESM modules to IIFE format automatically.

What It Does

The ESM Bundler Service:

  • ✅ Converts ESM modules to IIFE format
  • ✅ Handles nested dependencies automatically
  • ✅ Minifies the output for smaller size
  • ✅ Caches results for fast subsequent requests
  • ✅ Provides direct CDN URLs for optimal performance

Service URL

https://esm-bundler.vercel.app/api/bundle

Basic Usage

Request:

curl -X POST https://esm-bundler.vercel.app/api/bundle \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://esm.sh/date-fns@3.6.0",
    "globalName": "dateFns",
    "minify": true
  }'

Response:

{
  "globalName": "dateFns",
  "cached": false,
  "size": 150000,
  "url": "https://esm.sh/date-fns@3.6.0",
  "blobUrl": "https://xyz.public.blob.vercel-storage.com/bundles/..."
}

Using the Bundled Library

You can use the returned blobUrl directly in your script configuration:

{
  code: `
    async function beforeRequest() {
      const formatted = dateFns.format(new Date(), 'yyyy-MM-dd')
      $request.headers['X-Date'] = formatted
    }
  `,
  libs: [
    "https://xyz.public.blob.vercel-storage.com/bundles/..."
  ]
}

API Parameters

ParameterTypeRequiredDefaultDescription
urlstring-ESM module URL (from esm.sh, unpkg, etc.)
globalNamestringauto-detectCustom global variable name
minifybooleantrueMinify the output code
includeCodebooleanfalseInclude code in response (use blobUrl instead)
defaultAccessPathstring-Extract nested property as main export

Advanced: Custom Global Names

Specify a custom global name for convention:

{
  "url": "https://esm.sh/lodash-es@4.17.21",
  "globalName": "_"
}

This makes the library available as _ instead of lodashEs.

Advanced: Nested Exports

Some libraries (like faker) have nested structures. Use defaultAccessPath to simplify access:

{
  "url": "https://esm.sh/@faker-js/faker@9.5.0",
  "globalName": "faker",
  "defaultAccessPath": "faker"
}

Without defaultAccessPath: faker.faker.internet.email()
With defaultAccessPath: faker.internet.email()

Supported ESM CDNs

  • esm.sh - Fast, reliable ESM CDN (recommended)
  • unpkg - NPM packages with ?module flag
  • jsdelivr - NPM packages with /+esm suffix
  • skypack - Optimized ESM CDN

Example: Converting date-fns

# Step 1: Convert ESM to IIFE
curl -X POST https://esm-bundler.vercel.app/api/bundle \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://esm.sh/date-fns@3.6.0",
    "globalName": "dateFns"
  }'
{
  "blobUrl": "https://xyz.blob.vercel-storage.com/bundles/date-fns-3.6.0.js",
  "globalName": "dateFns"
}
// Step 2: Use in your script
{
  code: `
    async function beforeRequest() {
      const now = new Date()
      $context.today = dateFns.format(now, 'yyyy-MM-dd')
      $context.nextWeek = dateFns.addWeeks(now, 1)
    }
  `,
  libs: [
    "https://xyz.blob.vercel-storage.com/bundles/date-fns-3.6.0.js"
  ]
}

Why Use the Bundler?

Without BundlerWith Bundler
❌ ESM not supported✅ Automatic IIFE conversion
❌ Manual bundling required✅ One API call
❌ Handle dependencies yourself✅ Dependencies included
❌ No caching✅ Built-in caching
❌ Large responses✅ Small responses via blobUrl

Library Loading Best Practices

1. Prefer Built-in Libraries

Built-in libraries are pre-loaded and optimized. Always choose them over predefined or external alternatives:

// ✅ Good - use built-in Luxon for dates
const tomorrow = luxon.DateTime.now().plus({ days: 1 });
 
// ❌ Bad - loading Moment or DayJS
libs: ["https://cdn.jsdelivr.net/npm/moment/moment.min.js"];
 
// ✅ Good - use built-in Ky for HTTP
const data = await ky.get("https://api.example.com/data").json();
 
// ❌ Bad - loading Axios
libs: ["https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"];
 
// ✅ Good - use built-in Zod for validation
const schema = z.object({ email: z.string().email() });
 
// ❌ Bad - loading Validator
libs: ["https://cdn.jsdelivr.net/npm/validator/validator.min.js"];

Why? Built-in libraries are:

  • Already loaded (zero network overhead)
  • Faster execution (no additional HTTP requests)
  • Always available (no configuration needed)
  • Modern and actively maintained

2. Use Predefined Libraries When Available

Predefined libraries are tested and optimized for ReAPI:

// ✅ Good - use predefined CryptoJS
// Just click "Add Library" in the editor
 
// ❌ Bad - loading from random CDN
libs: ["https://unknown-cdn.com/crypto.js"];

3. Specify Versions in URLs

Always pin to specific versions to avoid breaking changes:

// ✅ Good - specific version
libs: ["https://cdn.jsdelivr.net/npm/library@1.2.3/dist/lib.min.js"];
 
// ❌ Bad - using @latest or no version
libs: ["https://cdn.jsdelivr.net/npm/library/dist/lib.min.js"];

4. Use ESM Bundler for Modern Libraries

For libraries without IIFE/UMD builds:

// ✅ Good - convert via bundler first
libs: ["https://esm-bundler.vercel.app/api/bundle?url=..."];
 
// ❌ Bad - trying to use ESM directly
libs: ["https://esm.sh/modern-library/+esm"];

5. Minimize External Dependencies

Each external library adds load time:

// ✅ Good - use built-ins
const formatted = luxon.DateTime.now().toFormat("yyyy-MM-dd");
 
// ❌ Bad - loading unnecessary library
libs: ["https://cdn.jsdelivr.net/npm/date-fns@3/dist/date-fns.min.js"];

Troubleshooting

Library Not Available in Script

Problem: Library is loaded but ReferenceError: libraryName is not defined

Solution: Check the library’s global name in its documentation or inspect the bundled file:

// Some libraries use different global names:
// - lodash → _ (not lodash)
// - moment → moment ✅
// - axios → axios ✅
// - jQuery → $ or jQuery

CORS Errors

Problem: Failed to load script: CORS policy

Solution: Use CDNs that support CORS (all recommended CDNs do). Avoid loading from:

  • file:// URLs
  • Localhost URLs
  • Servers without CORS headers

Library Version Mismatch

Problem: Library works locally but fails in ReAPI

Solution: Ensure you’re using the same version and format:

// ✅ Match versions exactly
libs: ["https://cdn.jsdelivr.net/npm/library@1.2.3/dist/lib.min.js"];

ESM Import Errors

Problem: Cannot use import statement outside a module

Solution: Use the ESM Bundler Service to convert:

# Convert the ESM module first
curl -X POST https://esm-bundler.vercel.app/api/bundle \
  -d '{"url": "https://esm.sh/your-library"}'


Summary

Built-in Libraries (Always Available):

  • Lodash (_), Faker, Zod (z), Ky, Luxon

💡 Always prefer built-in libraries - They’re pre-loaded, faster, and require no configuration.

Predefined Libraries (One-Click Add):

  • CryptoJS, DayJS, Axios, Moment, Validator, Turf.js, Numeral
  • Note: Consider using built-in alternatives (Luxon over Moment/DayJS, Ky over Axios, Zod over Validator)

Custom Libraries:

  • Load any IIFE/UMD library from a public URL
  • Use ESM Bundler for modern ESM-only libraries

ESM Bundler Service:

  • Converts ESM modules to IIFE format
  • Free, cached, and optimized
  • Available at https://esm-bundler.vercel.app/api/bundle