Blog

How to Execute JavaScript in Microsoft Power Automate

Microsoft Power Automate is a powerful workflow automation tool, but it has one major limitation: there's no native way to execute JavaScript code directly. When you need complex data processing, API calls, or custom logic, you quickly hit a wall.

The good news: CustomJS makes it easy to integrate JavaScript into Microsoft Power Automate. Through a simple API connection, your flows can execute JavaScript code without relying on external services like Azure Functions. This saves time, reduces complexity, and makes your workflows more flexible.

This guide shows you how to use JavaScript in Microsoft Power Automate – from setting up your API key to practical applications in real workflows.

TL;DR

  • Microsoft Power Automate doesn't support native JavaScript – CustomJS fills this gap with a simple API integration.
  • With the CustomJS connector for Power Automate, you can execute JavaScript code directly in your flows.
  • Setup takes less than 5 minutes: get your API key, add the connector, execute code.
  • Common use cases: data processing, API calls, JSON manipulation, date calculations, and complex business logic.
  • CustomJS offers 600 free requests per month – perfect for small to medium workflows.

Why JavaScript in Microsoft Power Automate?

Microsoft Power Automate offers many pre-built actions, but sometimes they're not enough. When you need to perform complex calculations, call external APIs, or transform JSON data, you quickly reach the limits of native functions.

JavaScript is the ideal solution for these scenarios. It's flexible, widely used, and can handle virtually any task that comes up in a workflow. With CustomJS, you can execute JavaScript code directly in Microsoft Power Automate without setting up additional infrastructure like Azure Functions.

This not only saves time but also makes your workflows more maintainable and easier to understand.

Step 1: Create Your CustomJS API Key

Before you can execute JavaScript in Microsoft Power Automate, you need an API key from CustomJS. Setup is straightforward:

  1. Go to app.customjs.io and create a free account.
  2. After signing in, find your API key in the dashboard under "API Keys".
  3. Copy the key – you'll need it in Power Automate shortly.

The free plan offers 600 requests per month, which is more than enough for most workflows. For larger projects, flexible paid plans are available.

Step 2: Add CustomJS Action to Microsoft Power Automate

Now you'll add the CustomJS action to your Microsoft Power Automate flow. This allows you to execute JavaScript code directly within your workflow.

CustomJS Action in Power Automate
CustomJS action in a Power Automate flow

Create a Power Automate Flow

  1. Open Power Automate and create a new flow (e.g., "Instant cloud flow").
  2. Add a new action and search for "CustomJS".
  3. Select the "Execute JavaScript" action.
  4. Create a connection using your API key from Step 1.

Configure the Action

The CustomJS action has three main fields:

  • Input: Data passed into your JavaScript code (accessible as input object)
  • JavaScript Code: Your custom JavaScript code
  • Return Type: Expected output format (JSON, String, etc.)
CustomJS Configuration in Power Automate
Configuring input and JavaScript code in the CustomJS action

Step 3: Execute JavaScript Code

Now you can execute any JavaScript code in Microsoft Power Automate. Here are some practical examples:

Example 1: Calculate Future Dates

Calculate a date 30 days from now:

const today = new Date();
const futureDate = new Date(today.setDate(today.getDate() + 30));
return futureDate.toISOString();

Example 2: Process JSON Data

Filter and transform JSON data:

const data = [
  {name: 'Anna', age: 28},
  {name: 'Max', age: 35},
  {name: 'Lisa', age: 22}
];

const filtered = data.filter(person => person.age > 25);
return JSON.stringify(filtered);

Example 3: API Call with Error Handling

Call an external API and handle errors gracefully:

try {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  
  return {
    success: true,
    data: data
  };
} catch (error) {
  return {
    success: false,
    error: error.message
  };
}

Example 4: Use Dynamic Inputs

You can pass variables from your Power Automate flow into the JavaScript code using the input object:

// Access input values
const firstName = input.firstName;
const lastName = input.lastName;

// Process and return
return `${firstName} ${lastName}`.toUpperCase();

In the Power Automate action, you would pass a JSON object like:

{
  "firstName": "John",
  "lastName": "Doe"
}

Practical Use Cases

JavaScript in Microsoft Power Automate opens up numerous possibilities. Here are some proven use cases:

1. Data Validation and Cleaning

Validate email addresses, phone numbers, or other inputs before accepting them into your system:

const email = input.email;
const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

return {
  valid: isValid,
  email: email,
  message: isValid ? 'Valid email' : 'Invalid email format'
};

2. Complex Calculations

Perform calculations that would be too cumbersome with Power Automate expressions:

const price = input.price;
const tax = input.taxRate;
const discount = input.discount;

const subtotal = price * (1 - discount);
const total = subtotal * (1 + tax);

return {
  subtotal: subtotal.toFixed(2),
  tax: (subtotal * tax).toFixed(2),
  total: total.toFixed(2),
  currency: 'USD'
};

3. API Integration

Connect to APIs that Power Automate doesn't natively support:

const apiKey = input.apiKey;
const endpoint = input.endpoint;

const response = await fetch(endpoint, {
  headers: {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  }
});

const data = await response.json();
return data;

4. Text and String Manipulation

Process text with regular expressions or complex string operations:

const text = input.text;

// Create URL-friendly slug
const slug = text
  .trim()
  .toLowerCase()
  .replace(/[^a-z0-9]+/g, '-')
  .replace(/^-+|-+$/g, '');

return slug;

5. Date and Time Calculations

Work with timestamps, time zones, and complex date calculations:

const startDate = new Date(input.startDate);
const endDate = new Date(input.endDate);

const diffMs = endDate - startDate;
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
const diffWeeks = Math.floor(diffDays / 7);

return {
  days: diffDays,
  weeks: diffWeeks,
  months: Math.floor(diffDays / 30)
};

Error Handling and Best Practices

To ensure your JavaScript integration in Microsoft Power Automate runs reliably, follow these best practices:

1. Always Include Error Handling

Use try-catch blocks to catch errors:

try {
  // Your code here
  const result = processData(input);
  return {
    success: true,
    data: result
  };
} catch (error) {
  return {
    success: false,
    error: error.message
  };
}

2. Validate Inputs

Always check that expected inputs are present:

if (!input || !input.value) {
  return {
    error: 'Missing required input: value'
  };
}

// Process here
const result = input.value * 2;
return result;

3. Await Async Results

When using asynchronous code (like fetch or API calls), always await the result before returning:

// ❌ Wrong: returns a Promise
return fetch(input.url).then(res => res.json());

// ✅ Correct: await and return the data
const response = await fetch(input.url);
const data = await response.json();

return {
  statusCode: response.status,
  data: data
};

4. Mind the Timeouts

CustomJS has a 30-second timeout per request. For longer operations, split your code or use asynchronous processing.

5. Remove Inline Comments

While inline comments usually work, they can sometimes cause issues. Consider removing them if you encounter problems:

// ⚠️ May cause issues
// return full name
return input.firstName + " " + input.lastName;

// ✅ Better
return input.firstName + " " + input.lastName;

CustomJS vs. Azure Functions

Many Microsoft Power Automate users turn to Azure Functions to execute JavaScript. However, CustomJS offers several advantages:

CriteriaCustomJSAzure Functions
Setup Time5 minutes30-60 minutes
InfrastructureNone requiredAzure account + deployment
Cost (small scale)Free (600/month)From ~$5/month
MaintenanceNoneUpdates, monitoring
ScalingAutomaticManual configuration

For most use cases, CustomJS is the faster and more cost-effective solution. Azure Functions only make sense at very high volumes or if you're already deeply invested in the Azure ecosystem.

Frequently Asked Questions

1. Can I use npm packages in CustomJS?

Yes, CustomJS supports many common npm packages. Most standard libraries like lodash, moment.js, or axios are available. For specific packages, contact support.

2. How secure is executing JavaScript through CustomJS?

CustomJS executes code in isolated environments. Your data is transmitted encrypted and not stored. The service is GDPR compliant.

3. Are there limits for code execution?

Yes, each request has a 30-second timeout and a maximum payload size of 10 MB. For most workflows, this is more than sufficient.

4. Can I use the code on other platforms too?

Yes, CustomJS works with any platform that supports HTTP requests. This includes Make.com, n8n, Zapier, and many others.

5. What happens if I exceed the free limit?

After 600 requests per month, additional requests are blocked until you upgrade to a paid plan. There are no hidden costs or automatic upgrades.

6. Can I test the code locally before using it in Power Automate?

Yes, CustomJS offers a web interface where you can test code before integrating it into your workflows. This saves time when debugging.

Conclusion

Using JavaScript in Microsoft Power Automate has never been easier. With CustomJS, you can integrate complex logic, API calls, and data processing into your workflows in just a few minutes – without additional infrastructure or complicated setups.

The combination of Microsoft Power Automate and CustomJS makes your automations more flexible, maintainable, and powerful. Whether you need to validate data, call external APIs, or perform complex calculations – JavaScript is the solution.

The free plan with 600 requests per month is sufficient for most projects. For larger workflows, flexible paid plans are available that grow with your requirements.

Start for free now and take your Microsoft Power Automate workflows to the next level.

Related Articles

Continue reading on similar topics

Best Screenshot APIs
·Comparison

Best Screenshot APIs

A deep dive into the top 5 screenshot APIs for 2025, comparing features, pricing, and performance to help you choose the best one.

screenshotapicomparison
CustomJS vs. 0CodeKit
·Comparison

CustomJS vs. 0CodeKit

If you want to improve your workflow in Make with JavaScript, there are some powerful tools available. Two of the best options are 0CodeKit and CustomJS.

comparisonmakeautomation
Airtable Accounting for Freelancers
·Guide

Airtable Accounting for Freelancers

Cost-effective alternative to QuickBooks & FreshBooks. Automatic PDF invoice generation with n8n, Make.com, or API integration.

airtableinvoiceaccounting
CustomJS vs. IFTTT
·Comparison

CustomJS vs. IFTTT

Explore CustomJS as a powerful IFTTT alternative. See how it compares to IFTTT for custom and advanced automation and which tool suits your needs.

comparisonautomationifttt
Pricing Comparison
·Pricing

Pricing Comparison

Automate complex tasks without blowing your budget! Learn how Make, Zapier, & n8n enable custom JS automation at various price points.

pricingcomparisonmake
Make vs. Zapier vs. n8n
·Comparison

Make vs. Zapier vs. n8n

Choosing the right workflow automation tool between Make, Zapier, and n8n depends on your tech comfort, task complexity, and budget.

comparisonmakezapier