Server-Side JavaScript
What SSJS is in Marketing Cloud Engagement, where and when it runs, what the Core library and the Platform class expose, and its limits.
A private bank publishes its clients’ portfolio report every quarter and wants two things: a sign-up page that greets the client by name, and a nightly process that goes over the table of report subscribers and fails with a readable message when something breaks. Where is that code written in Marketing Cloud Engagement, at what moment does it run, and how does it reach the account’s data?
What it is, and where it runs
Server-Side JavaScript (SSJS) is JavaScript that Marketing Cloud Engagement processes on its own servers instead of sending it to the browser. The developer guides put it as a contrast: instead of the browser rendering the JavaScript on the client-side computer, Engagement processes SSJS on the server side.
That is where the two consequences that govern everything else come from. What SSJS does not have: it does not work with the Document Object Model (DOM) — the tree of objects a browser uses to represent the page — and it does not function with external libraries. What it does: everything native to JavaScript, and the guides list it, arrays, math functions, the EVAL function and try catch blocks.
The moment of execution is fixed: Engagement executes SSJS at the time the content is rendered. And the reach is bounded by what the libraries open: SSJS can only access the .NET CLR (Common Language Runtime) objects exposed through the documented libraries, and an attempt to reach another one results in an error.
For the code to run on the server, the tag has to say so. It is the only required parameter and leaving it out has a consequence worth reading verbatim: “If you don’t specify this parameter, the browser tries to execute it, which results in errors”.
<script runat="server">[Add your SSJS code here]</script>
The tag takes three more parameters, in lower case inside the code.
| Parameter | What it sets, per the guides |
|---|---|
| runat | That the code runs at the server. Required |
| language | The block’s language: JavaScript or AMPscript. JavaScript by default |
| executioncontexttype | Get or Post. Get by default |
| executioncontextname | A named context to execute. The guides do not explain what that is |
SSJS personalization strings
SSJS has its own tags for inserting a value into rendered content, separate from calling a function. The guides call them personalization tokens and there are three. A word on vocabulary: the subscriber is the recipient of a send, a name these guides use without defining it and which the contact model page documents.
| Tag | What it references, per the guides |
|---|---|
ctrl:field |
Subscriber attributes, system attributes and sendable data extension fields |
ctrl:var |
SSJS or AMPscript variables |
ctrl:eval |
JavaScript expressions, as content substitutions |
All three take the same four attributes.
| Attribute | What it does, per the guides |
|---|---|
name |
Identifies the attribute, the field or the variable |
default |
The value the expression returns if the data source is null or an empty string |
format |
A format for the string; it takes the standard .NET numeric and datetime ones |
language |
javascript or ampscript; javascript by default |
The guides’ examples: <ctrl:field name="AttributeName" /> for an attribute, <ctrl:var name="JSVar" /> for an SSJS variable, <ctrl:var name=@AmpVar /> for an AMPscript one — the at sign is part of the name — and <ctrl:eval>"a".toUpperCase() + "B".toLowerCase()</ctrl:eval> for an expression.
The two library families
SSJS does not reach the account on its own: it does so, say the guides, through the Platform class and the Core library. They are SSJS’s own libraries and they exist so they can be updated while earlier versions are kept, so that code already written does not break. The Core library is loaded before it is used, with Platform.Load("core","1"); the Platform class objects exist outside it and do not ask for that load.
The split is not a matter of taste: the guides recommend it by context. The Platform class functions work in emails, mobile messages, CloudPages, microsites and landing pages, and because they exist outside the Core library they give faster performance than the rest of the SSJS functions; the Core library is left for pages and applications.
The guides split each family’s functions into groups, one per article. The Core library has twenty-two.
| Group | Group |
|---|---|
| Account | List |
| AccountUser | Portfolio |
| Content Area | Query Definition |
| Data Extension | Recipient |
| DateTime | Send Classification |
| Delivery Profile | Send |
| Sender Profile | |
| Events | Subscriber |
| Filter Definition | Template |
| Folder | Triggered Send |
| HTTP | Utilities |
The Platform class has eleven.
| Group | Group |
|---|---|
| API | Date and Time |
| Field and Attribute | Client Browser |
| HTTP | Utility |
| Content | AMPscript Variable |
| Data Extension | HTTP Property |
| Content Syndication |
For a data extension from the Core library, the guides’ example initializes the object with its external key, var birthdayDE = DataExtension.Init("birthdayDE"), and then uses its fields and rows sub-objects.
| Object | What it reaches, per the guides |
|---|---|
DataExtension, Core |
The fields and rows of a data extension, once initialized |
Recipient, Platform |
Attributes and fields of the sendable data extensions of the contact receiving the rendered content |
Request, Platform |
HTTP (hypertext transfer protocol) request properties: browser, IP (internet protocol) address, method, query string |
Response, Platform |
HTTP response properties, such as the content type or the character set |
On the API (application programming interface), the guides give an exact equivalence: the SSJS Add method invokes the web service’s Create, Remove invokes Delete, Update invokes Update and Retrieve invokes Retrieve.
WSProxy, and why the guides prefer it
The guides are explicit about their own library: the legacy methods for accessing SOAP (simple object access protocol) object data, including the ones the Core library uses, are primarily wrappers around AMPscript functions, and using them adds overhead because the code translates the data between two language runtimes. The WSProxy object is native to the platform, simpler, reduces that overhead and increases the speed of the calls, with syntax closer to JavaScript.
It is created in one line, var api = new Script.Util.WSProxy(), and the guides put one condition on it that they state and do not develop: it is available in all non-send contexts, with the same restrictions as any other SOAP API access method. What counts as a send context, no source quoted here says.
Limits, errors and what can bring a script down
A Script activity, which is the Automation Studio activity that runs SSJS, completes successfully unless an unhandled exception or an execution timeout stops it. Without intervention, raising an error makes the activity fail.
| Limit or restriction | What the guides say |
|---|---|
| Time | “SSJS activities time out after 30 minutes” |
| Recommended time | If the script consistently runs past ten minutes, they recommend another tool to transform the data |
| Memory | “A script activity will fail if it requires more than 6GB of memory” |
| Volume | Process in batches: load a chunk, handle it, release it and load the next |
| Data extensions | The Core library data extension functions do not support enterprise-level ones |
| External keys | They advise not going past 36 characters in a data extension external key |
Error handling has two routes that do not do the same thing. A try/catch block takes the expected errors and, say the guides, an error handled in the catch does not make the activity fail: that is where the detail is collected and written to a logging data extension, which is worth cleaning with a retention policy and reviewing regularly. But WSProxy raises no exception: it reports the error in a status field on the result, so that status has to be inspected or turned into an exception with ErrorUtil.ThrowWSProxyError.
AMPscript or SSJS
The two languages overlap, and the guides say so plainly: SSJS can duplicate AMPscript’s functionality, but SSJS also handles more advanced procedures, and they give arrays and advanced exception handling as the example. In the other direction, they close by saying that the vast majority of users can handle what they need to do with AMPscript. The language itself — its syntax and its functions — is the business of the sibling AMPscript page; only the boundary is here.
The split into rows is this page’s; each row quotes what the guides say.
| What has to be solved | What the guides recommend |
|---|---|
| Personalizing an email | AMPscript or Platform class functions, exclusively |
| Personalizing a page or an application | That is where they reserve the SSJS Core library |
| Inline personalization or a simple IF ELSE | AMPscript, for simplicity and efficiency |
| Unique content per subscriber | AMPscript handles it better than SSJS |
| Arrays or fine-grained exception handling | SSJS, for the advanced procedures |
| API calls outside a send context | WSProxy, for overhead and speed |
| A GET or a POST without loading the Core library | The Platform class content syndication functions |
And a warning the guides give twice: mixing the two languages is not something they encourage as a best practice, and for a landing page they advise picking one for the whole project. The bridge exists — the Platform class Variable object reads AMPscript variables declared in the JavaScript context — but its reason to exist, they say, is to let old AMPscript code live alongside SSJS.
Example: the portfolio report sign-up page
The bank wants the sign-up page personalized and a nightly pass over the table. Invented case; the order of the six steps is this page’s proposal, not the guides’, although every line of code is verbatim from a quoted source.
- The language. It is a page, so it falls in what the guides reserve for the SSJS Core library, and it is decided before writing so as not to mix it with AMPscript.
- The block. A
<script runat="server">on the landing page, because without that parameter the browser tries to execute the code and gives errors. - The greeting. The field tag with a default value, as the guides print it:
<ctrl:field name=FirstName default="client" />. - The figure. The variable tag with a format, the guides’ own example:
<ctrl:var name="CurrentSpend" default="0" format="C" />, where the C is a standard .NET numeric format. - The library.
Platform.Load("core","1");before any Core function, because those functions are not loaded to begin with. - The nightly pass. A Script activity that creates the
WSProxyobject, retrieves three columns from the data extension by its external key and turns the error status into an exception.
<script runat="server">
Platform.Load('core', '1');
var api = new Script.Util.WSProxy();
var customerKey = "0b744ffa-bab5-458d-9e7d-fb05a7873380";
var result = api.retrieve(
"DataExtensionObject[" + customerKey + "]",
[ "FirstName", "LastName", "EmailAddress" ]);
ErrorUtil.ThrowWSProxyError(result);
</script>
That block is verbatim from the guides, except the external key. What this page cannot promise is that pasting it works: not one line has been executed, because checking that needs a real Marketing Cloud Engagement account. The example claims only what its source says about each instruction.
One warning, and it is a reading by this page and not an execution: the fragment that same article uses to illustrate batch processing, read as JavaScript, uses two variables it does not declare and wraps the retrieve in a condition that is false on the first pass, so it retrieves nothing. The advice to process in batches is given here by quoting the source; its fragment is not copied as a model.
Before going to production
- The language decided for that piece, AMPscript or SSJS, and not both (see “AMPscript or SSJS”).
- The block marked to run on the server, and the context parameters set if they are needed (see “What it is, and where it runs”).
- The family chosen by context: Platform class in emails and mobile messages, Core library in pages and applications (see “The two library families”).
- The API calls made with
WSProxywherever the context is not a send one (see “WSProxy, and why the guides prefer it”). - Expected errors inside a try/catch, and the
WSProxystatus inspected or thrown withErrorUtil.ThrowWSProxyError(see “Limits, errors and what can bring a script down”). - Time measured against the thirty-minute cap and the ten-minute recommendation, and large data processed in batches (same section).
- Checked that the data extensions the script touches are not enterprise-level and that their external keys do not go past 36 characters (same section).
- Tested in a real account before publishing: nothing this page says replaces a run (see “Example: the portfolio report sign-up page”).
Official sources
- Get Started with Marketing Cloud Engagement APIs and Programmatic Languages — Developer guides (opens in a new tab)
- Scripting Language References — Developer guides (opens in a new tab)
- Server-Side JavaScript — Developer guides (opens in a new tab)
- SSJS Syntax Guide — Developer guides (opens in a new tab)
- Data Extension Functions (Core library) — Developer guides (opens in a new tab)
- Retrieve — Developer guides (opens in a new tab)
- Subscriber Functions — Developer guides (opens in a new tab)
- HTTP Functions (Core library) — Developer guides (opens in a new tab)
- Utilities Functions — Developer guides (opens in a new tab)
- Platform Functions — Developer guides (opens in a new tab)
- API Functions (Platform class) — Developer guides (opens in a new tab)
- Field and Attribute Functions — Developer guides (opens in a new tab)
- Data Extension Functions (Platform class) — Developer guides (opens in a new tab)
- AMPscript Variable Functions — Developer guides (opens in a new tab)
- HTTP Properties Functions — Developer guides (opens in a new tab)
- Client Browser Functions — Developer guides (opens in a new tab)
- Platform Content Syndication Functions — Developer guides (opens in a new tab)
- Use Server-Side JavaScript with AMPscript — Developer guides (opens in a new tab)
- Use Server-Side JavaScript via WSProxy with the SOAP API — Developer guides (opens in a new tab)
- Validate Your Server-Side JavaScript using WSProxy — Developer guides (opens in a new tab)