top of page

Not A Subscriber?

Every week, you'll get actionable tips to master Marketing Cloud, automate work, and improve your life.

Join 3,000+ people who get the MinuteAdmin Newsletter.

The Role of SSJS in Salesforce Marketing Cloud

By: Dennis Chau

Published September 27, 2023 ∙ 10 Minute Read



Table of Contents



 

Introduction


Why do people even care about SSJS?


The reason I wrote this article is because I once wondered the same.


After a quick Google search, expecting a simple answer, I still hit roadblocks in determining the reason that SSJS exists when AMPscript is another scripting language that can be utilized within Salesforce Marketing Cloud.


My hope is that I can inform others who have gone through a similar experience by providing an in-depth article about SSJS, answering the previous question, and any others that might arise.


But this journey wasn't just about compiling information. I’ve personally benefited from learning the language as well.


By studying SSJS, it has allowed me to gain a deeper understanding of Salesforce Marketing Cloud development and has broadened my skillset regarding server-side scripting languages.


This knowledge has not only enabled me to tackle more complex tasks and develop sophisticated solutions, but it has also made me a more valuable resource in the job market.


After hearing my story, I hope that you can reap the same rewards that I did from learning SSJS, but instead of having to search for information through many different resources, you can access it all here in this one article.


 

What Is SSJS?


SSJS stands for Server-Side JavaScript and is a scripting language used in Salesforce Marketing Cloud.


The language derives from JavaScript and includes a variety of APIs and objects specific to the Marketing Cloud platform.


The main difference is that SSJS code is executed on the server side, meaning it can access Marketing Cloud data and perform actions without any user involvement.


It allows you to accomplish tasks like manipulating data, retrieving data from external systems, creating and updating records, sending emails, and implementing custom logic.


Specific areas of Marketing Cloud where SSJS is most commonly used are CloudPages in Web Studio and Script Activities in Automation Studio.


By leveraging SSJS, developers can extend the capabilities of Marketing Cloud by building personalized workflows and optimizing complex tasks, resulting in improved customer engagement and enhanced marketing campaigns.


 

Why Is SSJS Important?


SSJS is an important part of Marketing Cloud for several reasons.


First, SSJS allows developers to easily interact with a variety of Marketing Cloud components, like Data Extensions, REST and SOAP APIs, Custom Activities, Content Builder, Journey Builder, Automation Studio, and Analytics and Reporting.


This simplifies the process of accessing and manipulating data across different areas of Marketing Cloud, leading to more streamlined workflows, optimized data management, and improved overall efficiency.


Second, SSJS gives developers the ability to handle complex data processing operations like data retrieval, importing and exporting, segmentation, deduplication, and more.


This is useful for uncovering insights, segmenting audiences, and carrying out data-driven analysis to improve marketing strategies.


Finally, SSJS provides more security when handling personally identifiable information by running code on the server side.


This approach restricts client-side access to sensitive data and safeguards customer information.


All in all, by effectively leveraging SSJS, developers can create personalized, effective, and secure marketing campaigns.


 

SSJS vs AMPscript


Giving developers the ability to choose between two different scripting languages in Marketing Cloud can lead to indecisiveness as to which language to choose for their specific needs.


To help with this, I’ve highlighted the main differences between SSJS and AMPscript through use cases and key features of each language:


Use Cases:

​Use Case

SSJS

AMPscript

Personalization

✔️

✔️

Data Retrieval

​✔️ (with more coding)

✔️

Advanced Programming

✔️

External Integrations

✔️

✔️

​Complex Logic

✔️

File Manipulation

✔️

Workflow Automation

✔️ (advanced scripting for workflows)

Content Blocks

✔️ (more complex)

✔️

Error Handling

✔️

Subscriber Management

​✔️ (basic operations)

✔️


Key Features of AMPscript:

Feature

Description

​Personalization

Dynamic content insertion based on subscriber data

Data Retrieval

Retrieving data from Data Extensions and subscriber attributes

Conditional Logic

Support for basic conditional statements

Content Blocks

Creating and managing reusable content blocks

Subscriber Management

Functions for subscriber management operations


Key Features of SSJS:

Feature

Description

Advanced Scripting

Support for advanced scripting and programming

External Integrations

Ability to make HTTP requests and integrate with external APIs

Complex Logic

Suitable for complex server-side logic and calculations

File Manipulation

Reading, writing, and manipulating files

Error Handling

Strong error-handling capabilities

To sum up, choosing between SSJS and AMPscript depends on how complex the use case is and the technical expertise of the user.


SSJS provides broader capabilities but requires a higher level of technical expertise.


On the other hand, AMPscript is user-friendly and ideal for most marketing-specific tasks but may not be suitable for anything too advanced.


A well-balanced combination of both languages would maximize the capabilities of a developer the most within Marketing Cloud.


 

How Does SSJS Work?


To write effective Server-Side JavaScript code, a solid understanding of its syntax and features is necessary.


Understanding the differences between SSJS blocks and inline SSJS, as well as gaining knowledge of SSJS’s Platform and Core Libraries, WSProxy, and the fundamental principles of SSJS logic, will help you achieve this.


SSJS Blocks: SSJS Blocks allow you to write SSJS code within an email, SMS, landing page, or script activity. The blocks need to be surrounded by <script> tags, and there is one required parameter, which is runat="server".


Code Example:

  • Declaring an SSJS block:

<script runat="server">
  // SSJS Code
</script>

Inline SSJS: Inline SSJS allows you to directly output content without the need for SSJS blocks. It can be achieved through three different versions of the 'ctrl' tag: 'ctrl:field' for retrieving values from attributes or data source fields, 'ctrl:var' for obtaining values from declared SSJS or AMPscript variables, and 'ctrl:eval' for inlining or embedding SSJS expressions to generate content.


Code Example:

  • Using different versions of the ‘ctrl’ tag to retrieve a field from a data source, access an SSJS variable, and convert a string to uppercase:

// Retreiving Field from Data Source
<ctrl:field name="CustomerID"/>

// Accessing SSJS Variable
<ctrl:var name="myVar"/>

// Converting String to Uppercase
<ctrl:eval>string.toUpperCase()</ctrl:eval>

Platform Library: The Platform Library provides additional functions exclusively for SSJS in Marketing Cloud. It allows developers to carry out tasks like retrieving and updating data extensions, sending emails, managing subscriber-related tasks, and accessing services specific to the platform. This library is selected by default and does not need to be loaded in order to be used. You should use this library if you’ll be including SSJS in an email or SMS.


Code Example:

  • Using the Platform Library to send an email using the Platform.Function.CreateObject() and Platform.Function.InvokePerform() functions:

<script runat="server">
  var emailDefinition = {
    To: 'recipient@example.com',
    Subject: 'Test Email',
    HTMLBody: '<p>This is a test email sent via SSJS.</p>'
  };
  
  var emailID = Platform.Function.CreateObject("Send", emailDefinition);
  Platform.Function.InvokePerform(emailID);
</script>

Output:

  • *If the email is successfully sent, then it will be delivered to the specified recipient*


Core Library: The Core Library offers a set of JavaScript functions built into the SSJS runtime within Marketing Cloud. It allows developers to carry out tasks like accessing subscriber attributes, manipulating data extensions, and sending emails. This library needs to be loaded in order to be used. You should use this library if you’ll be including SSJS in a landing page or application.


Code Example:

  • Using the Core Library to add a row to a data extension using the Rows.Add() function:

<script runat="server">
  // Load the Core Library
  Platform.Load("Core", "1");

  // Initialize the Data Extension object via ExternalKey
  var de = DataExtension.Init("myExternalKey");

  // Create an object representing the row data
  var rowData = {
    SubscriberKey: "12345",
    FirstName: "John",
    LastName: "Doe",
    Email: "johndoe@email.com"
  };

  // Add a new row to the Data Extension
  de.Rows.Add(rowData);

  // Display a success message
  Write("Row added to Data Extension successfully.");
</script>

Output:

  • Row added to Data Extension successfully.


WSProxy: WSProxy is a built-in script object within Marketing Cloud for interacting with SOAP objects using platform authentication. It uses SSJS and JSON syntax to make these calls within Script Activities or CloudPages. This object must be contained in a variable that you define in order to be used, and it is available in all non-send contexts within the platform. You should use this object if you’d like a simpler and faster alternative to making API calls.


Code Example:

  • Returning information on the structure of a SOAP API object using WSProxy’s describe method:

<script runat="server">
  // Load the Core Library
  Platform.Load("Core", "1");

  // Define the WSProxy object
  var prox = new Script.Util.WSProxy();

  // Define the SOAP Object for which you want to retrieve information
  var soapObjName = "DataExtension";

  // Define a function to describe the SOAP API object
  function describeGeneric(soapObjName) {
    var req = prox.describe(soapObjName);
    return req;
  }

  // Call the describeGeneric function to retrieve information about the DataExtension object
  var describeResult = describeGeneric(soapObjName);

  // Display the result
  Write("Result: " + Stringify(describeResult));
</script>

Output:

  • *Returns information about the SOAP API object, including its properties and their characteristics (left out because it’s too long to display here)*


Variables: Variables are used for data handling and manipulation. By using the keyword “var”, you can declare variables. They are capable of storing data types such as strings, numbers, arrays, or objects.


Code Example:

  • Storing a string in a variable and printing it using Platform.Response.Write():

<script runat="server">
  var greeting = "Hello, World!";
  Platform.Response.Write(greeting);
</script>

Output:

  • Hello, World!


Constants: Constants are fixed values that don’t change when a script is executed. By using the keyword “const”, you can declare constants.


Code Example:

  • Using a constant to represent the value of pi and calculating the area of a circle:

<script runat="server">
  const pi = 3.14159;
  var radius = 5;
  var area = pi * radius * radius;
  Platform.Response.Write("Area of the circle: " + area);
</script>

Output:

  • Area of the circle: 78.53975


Operators: There are different types of operators within SSJS that include arithmetic, comparison, logical, and assignment operators. They are used to perform operations on variables and values.


Code Example:

  • Using arithmetic and comparison operators to calculate the sum and check for equality:

<script runat="server">
  var num1 = 10;
  var num2 = 5;
  
  var sum = num1 + num2;
  Platform.Response.Write("Sum: " + sum);
  
  var isEqual = (num1 === num2);
  Platform.Response.Write("Are the numbers equal? " + isEqual);
</script>

Output:

  • Sum: 15

  • Are the numbers equal? false


Control Structures: Control structures allow you to manage the flow of SSJS code. Examples of control structures include statements such as if, else if, else, switch, and loop structures like for, for…in, while, and do while.


Code Example:

  • Using if, else if, and else statements to check if a number is positive, negative, or zero:

<script runat="server">
  var number = -5;
  
  if (number > 0) {
    Platform.Response.Write("The number is positive.");
  } else if (number < 0) {
    Platform.Response.Write("The number is negative.");
  } else {
    Platform.Response.Write("The number is zero.");
  }
</script>

Output:

  • The number is negative.


Functions: Functions are reusable code blocks. They allow you to store a piece of code that performs a single task inside a defined block and then call that code when you need it using a short command instead of having to type out the same code repeatedly.


Code Example:

  • Creating a custom function to calculate the area of a rectangle:

<script runat="server">
  function calculateRectangleArea(length, width) {
    return length * width;
  }
  
  var length = 5;
  var width = 3;
  var area = calculateRectangleArea(length, width);
  Platform.Response.Write("Area of the rectangle: " + area);
</script>

Output:

  • Area of the rectangle: 15


Objects: Objects are used to represent and manipulate data in a structured way. They hold a collection of related properties and methods.


Code Example:

  • Defining an object representing a person with properties and a greeting method, then using it to display the person's name and greeting:

<script runat="server">
  // Define a custom object to represent a person
  var person = {
    firstName: "Marc",
    lastName: "Benioff",
    age: 58,
    greet: function() {
      return "Hello, my name is " + this.firstName + " " + this.lastName + " and I am " + this.age + " years old.";
    }
  };

  // Access properties and methods of the object
  var fullName = person.firstName + " " + person.lastName;
  var greeting = person.greet();

  // Display the results
  Platform.Response.Write("Full Name: " + fullName + "<br>");
  Platform.Response.Write("Greeting: " + greeting);
</script>

Output:

  • Full Name: Marc Benioff

  • Greeting: Hello, my name is Marc Benioff and I am 58 years old.


Attributes: Attributes are used to store and access data relating to subscribers or objects. Subscriber attributes hold subscriber-specific information such as first name, last name, and email address.


Code Example:

  • Retrieving a subscriber's first name attribute and using it in the email content:

<script runat="server">
  var email = "subscriber@example.com";
  var subscriber = Subscriber.Init(email);
  var firstName = subscriber.Attributes.FirstName;
  Platform.Response.Write("Dear " + firstName.Value + ", ...");
</script>

Output:

  • If the subscriber's first name is "Bill", the output will be:

○ Dear Bill, …


Debugging: There are two main methods for debugging errors within SSJS code. The first one is to use the write() function, which displays what is passed in it to the frontend view. The second method involves using a try-catch block, which allows you to catch and handle exceptions during the execution of your code.


Code Example:

  • Making an API call to an invalid URL using the HTTP.Get() function and using a try-catch block to catch and handle any exceptions that may occur during the API call, displaying an error message if an exception is caught:

<!DOCTYPE html>
<html>
  <head>
    <title>Example Try-Catch Block in SFMC</title>
  </head>
  <body>
    <script runat="server">
      Platform.Load('Core', '1');

      try {
        // Simulate an API call to an invalid URL to trigger an exception
        var response = HTTP.Get('http://invalidurl');
      } catch (error) {
        // Error handling logic
        Write('An error occurred: ' + error.message + '<br><br>');
      }
    </script>
  </body>
</html>

Output (in the browser when previewing the CloudPage):

  • An error occurred: An error occurred while making the request. (Status Code: -1)


 

SSJS Real-World Use Case



Picture this scenario: You’re working as a developer for a university, and they want to use SSJS in Salesforce Marketing Cloud to enhance communications with students.


Specifically, the university would like you to create personalized and relevant communications for potential students, enrolled students, and alumni to increase engagement and build stronger relationships overall.


SSJS could be integrated into Marketing Cloud to accomplish these goals by incorporating features such as:


  • Automated Welcome Journey: If a potential student completes a contact form on the university’s website, SSJS can process it. It could handle form submission, verify data, and then trigger an automated welcome journey in Marketing Cloud. The journey itself could incorporate emails with tailored information like what program the student is interested in, campus facilities, and open house events.


  • Event Registration and Reminders: For events like university campus tours, SSJS can take care of the sign-up process and send automated reminders to students with more detailed event information and directions.


  • Academic Progress Updates: For university students who are already enrolled, SSJS can retrieve data from them. This could then be used to set up triggered personalized emails with academic progress updates that include information regarding grades, upcoming exams, and resources for academic support.


  • Alumni Engagement: To maintain strong relationships with university students who have already graduated (alumni), SSJS can be used. By retrieving data on the former students, the university can segment them based on the year they graduated or what field they studied in to send them targeted email messages.


Ultimately, educational institutions like colleges or universities could greatly benefit from using SSJS in Marketing Cloud to improve communications with all types of students.


This would result in an overall better experience for students when it comes to receiving personalized content and greater satisfaction with the institution.


 

Personal Journey



Prior to entering the realm of Salesforce Marketing Cloud development, I was interested in web development.


To build websites and web applications, I learned JavaScript, and it’s what gave me a head start when it came to learning SSJS because the two languages are so similar.


With a fundamental understanding of a scripting language already in place, I progressed further into SSJS by developing a study strategy that involves looking at SSJS-specific documentation, code examples, and writing out code in MCSnippets.


First, I browse through SSJS code snippets from both Mateusz Dabrowski’s and Ivan Razine’s websites to find which topic in SSJS I would like to learn more about.


Then, as I read through their code snippets, I refer back to the official Salesforce SSJS documentation to learn more about specific syntax or functions that I’m not too familiar with and to confirm their validity.


Finally, I get hands-on experience coding in SSJS by using the online playground MCSnippets, created by Pato Sapir, which allows you to work with programming languages in Marketing Cloud and preview the results without needing access to a Salesforce Marketing Cloud org.


I try to rewrite the previously mentioned code snippets from scratch in the online playground through my understanding of them and not solely through memorization.


This process involves trial and error without referencing the original code and helps me learn and remember solutions for similar problems more efficiently.


At this point in time, I have already covered the SSJS knowledge necessary for my main goal of being ready to take the Salesforce Marketing Cloud Developer certification exam, but I am still further developing my skills to continuously grow.


I’m doing this by learning more about advanced topics like SSJS API functions and how SSJS can be used to interact with JSON data.


 

Learn More About SSJS


Here is a 7-step plan on how you can gain an in-depth understanding of SSJS:


1. Understand the Fundamentals: Start by understanding the basics of SSJS. See how the language differs from standard JavaScript. Look at resources like official documentation to see what SSJS is capable of and discover different use cases.


2. Study Script Activities: Dive into Script Activities in Marketing Cloud, which gives you the ability to run SSJS in automation workflows. Discover methods, objects, and variables specific to Marketing Cloud’s implementation of SSJS.


3. Analyze Existing SSJS Code: Examine already-written SSJS code examples. Reverse engineer the code to understand its logic and purpose.


4. Hands-on Practice: Gain practical experience by writing SSJS code. Start by creating an automation that includes SSJS Script Activities. Then, transition from writing simple scripts to more advanced ones. Focus on gaining experience with fetching and manipulating data, sending out emails, and conditional logic.


5. Explore Platform & Core Libraries: Gain knowledge on Marketing Cloud’s SSJS Platform and Core Libraries. Understand the available functions and methods to see how they can be used in different scenarios.


6. Learn About WSProxy: Explore the functionality and capabilities of the WSProxy object within Marketing Cloud. Gain insight into its advantages over the legacy in-platform methods that were available beforehand, allowing you to make informed decisions on when and how to effectively leverage it.


7. Build Real-World Use Cases: Look for areas in your marketing workflows where SSJS can be leveraged to improve automation, personalization, or integration with external systems. Then, come up with solutions for each of these areas using SSJS.


 

SSJS Resources


Here are some useful links to learn more about SSJS:


 

Key Takeaways


To recap, this article discusses Server-Side JavaScript (SSJS) in Salesforce Marketing Cloud, explaining its significance, comparing it with AMPscript, and providing practical insights into how the language works.


SSJS allows developers to execute custom logic on the server side, enabling data manipulation, external system integration, email sending, and much more. It provides many capabilities and is generally used for more complex tasks.


While comparing SSJS with AMPscript, AMPscript is more user-friendly and geared towards simple tasks and personalization, while SSJS offers broader capabilities for complex operations but requires more technical expertise.


When learning SSJS, utilize a study strategy that involves looking at SSJS-specific documentation, code examples, and writing out code in MCSnippets.


Specifically, focus on learning about the difference between SSJS blocks and inline SSJS, the Platform and Core Libraries, WSProxy, variables, constants, operators, control structures, functions, objects, attributes, and debugging methods to gain a solid understanding of the language.

1 Comment


Guest
Sep 06

Thanks this is very helpful. Let me know a good way to connect with you on a SFMC project

Like

When You're Ready,
Here's How I Can Help
You:

3 Day Challenge

Goals are important. If you want help reverse engineering Marketing Cloud success into bite-size goals and tasks - start the 3 day challenge for free.

10_Bundlefor the 3rd time.png

Marketing Cloud Program

Real World Projects To Help You Pass Certifications And Become a Marketing Cloud Expert.

Marketing Cloud, Personal Development, & Time Freedom.

Every week, you'll get actionable tips to master Marketing Cloud, automate work, and improve your life.

Join 3,000+ people who get the MinuteAdmin Newsletter.

  • Youtube
  • LinkedIn
  • Facebook
  • TikTok

© 2024 by MinuteAdmin.

bottom of page