This is the second part in an ongoing series, please visit here to read the first article. This article is intended to give a general overview on SFMC Server-side JavaScript and its unique capabilities.

Background

First major point to make is that SFMC SSJS is here to stay and in fact may even play a bigger role as the platform gets more like Salesforce Core. I believe that there will be movement forward inside of the SFMC SSJS language within the next few years to help make it an even more powerful and relevant language.

As for the current state, I have found JavaScript version 1.5 most accurately reflects what is available in SFMC. Although, 1.5 is closest, there are still some differences – so do not take this version as the definitive guide to what works in SSJS. Especially keeping in mind that all capabilities related to the DOM and BOM do not work.

What is the Stigma?

The major complaint a lot of people have about SSJS is that it is less performant than AMPscript. The best practice declared by SFMC is if it is possible to utilize AMPscript instead, that you should. BUT, that does not mean you should never use SSJS in an email.

To an extent this best practice is true, but it is not as universal as you may think. A lot of the Platform functions that mimic AMPscript capabilities (Lookup, Upsert, etc) do have an added layer of translation inside of email, but this is not a process breaking difference.

The major reason for significant processing delays in emails is that SSJS is usually used in more complex ways than AMPscript, making precompilation inside of an email (the cool thing that makes mass email sending in SFMC so fast) less possible. AMPscript tends to be used for more simple things like personalizatoin or basic dynamic content, where SSJS is usually used more for complex parsing (JSON) and dynamic content/activity.

Something to keep in mind when choosing your language is that Landing Pages and CloudPages utilize a different rendering process from email, reducing the performance difference between SSJS and AMPscript. So although the general best practice for performant emails is to utilize AMPscript, but SSJS is more likely to be the preferred language in a web page. Especially when you throw WSProxy and the Core library into the mix.

SFMC Specific Functions

SFMC SSJS is separated into two different ‘sections’ for platform specific functions – Platform and Core library. Each has a very different purpose and unique capabilities. Below I will give a quick overview on these two sections, but will go into more detail on them in later articles.

Platform Library is very similar to AMPscript inside of its uses and applications. It is aimed to be used mostly for send time processing on email messages.

Core Library is very different from AMPscript and is focused more on simplified and controlled API calls to SFMC SOAP objects via built-in functions.

These two sections combined with native JS abilities are what makes up SFMC SSJS. So now that we know what it is, how do we use it?

Coding Basics

Declare Block

One of the first things you need to do in order to utilize SSJS is to set the appropriate tag to create a SSJS Block. There are a couple things to note before viewing the block:

  1. Tags are case insensitive
  2. Quotation marks are optional
  3. Scripting on each item is executed at time of rendering and then are expunged directly after. No variable states remain after rendering. (basically that you cannot share code/variables across iterations)

The declare block is as simple as using a <script> tag, similar to how you declare a Client-side JS block or the tag-based AMPscript delimiter (not the Standard AMPscript delimiter %%[ ]%% that most people use). There are four parameters that can be used on this tag, but only one is required. The minimum you need for your declare block is just to note that this script should be run at the server…which is really as easy as that.

<script runat=server>
    [SSJS code]
</script>

The other three parameters are:

  1. Language
  2. ExecutionContextType
  3. ExecutionContextName

Language

This parameter is where you specify if the code inside the block is JavaScript or AMPscript. The script tags inside of SFMC only allow those two languages. As the default value for this parameter is JavaScript, it is not a required parameter to be used in the declaration of the script tag.

ExecutionContextType

In a nutshell, execution context is the method of the HTTP request made to the server. So if you submitted a form and it landed on the page, it likely sent a POST request. If you used your web browser to bring up a page, it likely was a GET request. Currently this parameter only accepts those two values (GET | POST) to be inserted. The default, if empty, is to set this to GET.

ExecutionContextName

This basically sets a name to the script block you are creating. If you name a script block via this parameter, it will only run when the request context contains this name inside of it. Otherwise this block will not execute on load. This can be beneficial for a page POSTing to itself or if its behavior is different depending on where they are coming from, etc. But in general, most people will not have a use case for this parameter.

For some more information on Execution Context, you can check out the SFMC AMPscript overview on it here

Here is an example of the full syntax being used on a declare block:

<script runat=server language="JavaScript" executioncontexttype="Post" executioncontextname="myBlock">
  [SSJS code]
</script>

Inline and Embedded SSJS Content

Similar to AMPscript, SSJS can push content directly to output without requiring script blocks. Aside from that similarity though, the process and syntax is quite different for SSJS compared to AMPscript. For instance, these ‘personalization tokens’ are used for:

  1. Subscriber and System Attributes
  2. Send-Time Data Source Fields
  3. Variables
  4. Functions
  5. JavaScript code expressions

Where in AMPscript, the syntax only handled Attributes and fields. The rest had to use an ‘inline’ syntax in order to output the value without creating a block. Another cool thing to note is that these ‘tokens’ can actually also output AMPscript variables as well as SSJS.

Each of these ‘tokens’ utilize a specialty tag named ‘ctrl’. But this tag is broken into 3 parts and cannot be used as a standalone. See below for supported tag names:

  1. ctrl:field – grabs a value from an attribute or data source field
  2. ctrl:var – grabs a value from a declared SSJS or AMPscript variable
  3. ctrl:eval – inlines/embeds SSJS expressions to create content

Attributes for ctrl tags:

  1. Name – Identifies the attribute, sendable data field or variable to be used. It is required for field and var calls.
  2. Default – (Optional) default value for the tag. This is returned if data source is null or empty
  3. Format – (Optional) Specify formatting to use on the value inside the string.
  4. Language – Specifies language of the expression used. Only accepts javascript and ampscript. default is javascript.

Atrribute/Field Syntax Samples:

Directly Outputs Value – similar to Write() function

Gather a Subscriber Attribute:

<ctrl:field name="SubscriberKey" />

Get a Field from Data Source:

<ctrl:field name="CustomerID" />

Gather a Subscriber Attribute with a default value:

<ctrl:field name="SubscriberKey" default="[email protected]" />

Gather a Subscriber Attribute with a default and format:

<ctrl:field name="SubscriberKey" default="[email protected]" format="g" />

Variable Syntax Samples:

Directly Outputs Variable – similar to Write() function

Accessing a SSJS Variable:

<ctrl:var name="myVar" />

Accessing an AMPscript Variable:

<ctrl:var name="@AmpscriptVar" />

Accessing an AMPscript Variable with a default:

<ctrl:var name="@AMPscriptVar" default="No Variable Exists" />

Accessing an AMPscript Variable with a default and format:

<ctrl:var name="@AMPscriptVar" default="No Variable Exists" format="g" />

Expression Evaluation Syntax Samples

Interpret strings of JavaScript source code, evaluating them to produce a value – similar to eval() function. Here is a good resource for expressions and operators that can be used. Most native methods and functions (allowed in SSJS) should work as well.

Forces string to Uppercase (can also do toLowerCase(), etc.)

<ctrl:eval>string.toUpperCase()</ctrl:eval>

Forces string to Uppercase with a default

<ctrl:eval language=javascript default="STRING">string.toUpperCase()</ctrl:eval>

Forces string to Uppercase with a default and format

<ctrl:eval language=javascript default="STRING" format=G>string.toUpperCase()</ctrl:eval>

You can use full-function syntax or equivalent simple expression syntax. For example the below output the same:

return string.toUpperCase()
string.toUpperCase()

Using SSJS with AMPscript

One major thing to note about this is that it is not best practice at all to mix the coding languages together. SFMC explicitly states that you should only use one or the other in your landing pages or other projects as using them together is not considered best practice. This capability was added in to help those with old AMPscript code make that code work in conjunction with SSJS as necessary.

Pass Variables from AMPscript to SSJS

In order to pass variable values across the languages, you would use the Core Variable functions. These will allow you to pass information from AMPscript to SSJS or to utilize SSJS to gather the value of an AMPscript variable.

In order to utilize these, you will need to load the Core library (Platform.Load('Core','1.1.1')) as they are Core functions – more details on this will be provided in future articles.

Variable.GetValue
This function is used to grab an existing AMPscript variable and pass it into a SSJS variable.

var ampVar = Variable.GetValue('@myAMPVariable');

Variable.SetValue
This function is used to assign a value to an AMPscript variable via SSJS

Variable.SetValue('mySSJSVar','@myAMPvar');

Span SSJS Blocks with AMPscript Control Statements

SSJS blocks can span these content types:

  • HTML
  • Text
  • Personalization String
  • AMPscript

A major note is that you will need to close each script block prior to moving to the next content type. For instance, you cannot run AMPscript inside of a SSJS block, regardless if you declare it via the short hands %%[]%% or not. This code would be considered SSJS still and likely produce errors or at least unexpected behavior.

Example:

<script runat=server>
	var count = 0;
	if(count < 1) {
</script>

<!-- Transition to HTML -->
<p>If Case </p>

%%[
	/* Transition to AMPscript */
	set @v1=0

	for @v1=1 to 5 do
]%%

<script ruant=server>

	//Transition back to SSJS
	} else if (count > 1) {
</script>

<!-- Transition back to HTML -->
<p> Else If Case </p>

<script runat=server>

	//Transition to SSJS again
	} else {
</script>

<!-- Transition again to HTML -->
<p>Else Case</p>

<script ruant=server>

	//Transition final time to SSJS
	}
</script>

What is a WSProxy anyway?

WS stands for WebSocket protocol, which provides a way of creating web applications that support real-time bidirectional communication with clients and servers. Pretty much this boils down to its like a telephone from your environment to the target environment.

Proxy stands for a proxy server that acts as an intermediary between client and another service. Imagine the Proxy server to be the customer service department at a company that gets your complaint and then contacts the corresponding department to find the resolution you need. They then take that info and bring it back to you.

WSProxy is a ‘new’ script object that is native to the platform and is simpler to use than most of the legacy methods to access SOAP object data. It reduces overhead and increases the speed of your API calls, while keeping the security that it is all authenticated via your platform and not user/pass or external tokens. WSProxy usage syntax is much more like Javascript and easier to pick up and understand (In my opinion, this is true regardless if you know JS beforehand or not). WSProxy is available in all non-send contexts and has same restrictions in place as all other SOAP API access methods.

As such a huge and impactful capability, I will be dedicating a future article to WSProxy, so be on the lookout to get more details then.

That was all for the basics of SFMC SSJS! I hope you enjoyed reading it and find it as useful as I have. Keep a look out for the next article, which should be about the Platform Library and all of its capabilities and uses.

Tags: , , , ,
Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Sebastiaan Simons
Sebastiaan Simons
3 years ago

Thanks for these articles! Really interesting.
Keep it up 🙂

trackback
SFMC Server-Side JavaScript 3: Platform Library | Gortonington
3 years ago

[…] Previous Previous post: […]

Alex Diamond
Alex Diamond
8 months ago

Thanks for these articles. I’m struggling to get my head around SSJS and these are a really good starting point. Really appreciate them.