AMPscript is great for small pieces of personalization. When the logic gets longer, with loops, objects, JSON or API calls, Server-Side JavaScript (SSJS) is often easier to read and maintain. This guide covers how SSJS works in Marketing Cloud Engagement, which library to use where, and the patterns I use most for email and CloudPages.
How SSJS runs
SSJS runs on Marketing Cloud's servers, not in the subscriber's inbox or browser. By the time the email is delivered, the script has already run and only the output is left. That means:
- There is no DOM. You can't use
document,windowor anything a browser gives you. - You can't load outside JavaScript libraries.
tryandcatchwork, and you should use them.
Every SSJS block starts with a script tag that has runat="server":
<script runat="server">
// your code here
</script> Platform library or Core library?
SSJS has two main libraries.
| Library | Where to use it | How to load it |
|---|---|---|
| Platform | Email and SMS messages, plus CloudPages | Available by default |
| Core | CloudPages, landing pages and Script activities | Platform.Load("core", "1"); |
The rule is simple: in messages, use Platform functions. Core functions are for pages and Script activities in Automation Studio, where you are working with data rather than rendering an email for one subscriber.
Read a value from a data extension
The function you will use most is Platform.Function.Lookup. It takes the data extension name, the column you want back, the column to search, and the value to search for.
<script runat="server">
try {
var subscriberKey = Platform.Recipient.GetAttributeValue("_subscriberkey");
var tier = Platform.Function.Lookup(
"Loyalty_Members", // data extension
"Tier", // column to return
"SubscriberKey", // column to search
subscriberKey // value to match
);
if (!tier) {
tier = "Member";
}
// Make the value available to AMPscript as @tier
Platform.Variable.SetValue("@tier", tier);
} catch (e) {
Platform.Variable.SetValue("@tier", "Member");
}
</script>
Hi %%=v(@tier)=%% member, here is what's new this week. Notice the fallback. If the lookup finds nothing or throws an error, the email still renders with a safe default. A send should never fail because one subscriber is missing a row.
Read several rows
Platform.Function.LookupRows returns every matching row, up to 2,000. If you need the rows sorted or limited to a set number, use LookupOrderedRows instead.
<script runat="server">
var subscriberKey = Platform.Recipient.GetAttributeValue("_subscriberkey");
// 3 rows, newest first
var orders = Platform.Function.LookupOrderedRows(
"Orders",
3,
"OrderDate desc",
"SubscriberKey",
subscriberKey
);
var html = "";
for (var i = 0; i < orders.length; i++) {
html += "<li>" + orders[i]["ProductName"] + "</li>";
}
Platform.Variable.SetValue("@orderList", html);
</script>
<ul>%%=TreatAsContent(@orderList)=%%</ul> ⚠️ Escape data you didn't write
If a field can contain text typed by a customer, don't drop it straight into HTML. Clean it first, or keep the output in AMPscript and use functions built for safe output.
Call an external API
SSJS can call web services. Which function you use depends on where the code runs.
Script.Util.HttpGetis for messages. Marketing Cloud caches the response during a send, so the same URL isn't called once per subscriber.Script.Util.HttpRequestis the better fit for CloudPages and Script activities. It supports GET, POST, PUT, PATCH and DELETE, lets you set headers, and returns a full response object. It doesn't cache content, so in an email it would call the API once for every subscriber.
Some limits to keep in mind with HttpRequest: it only works over ports 80 and 443, and send() times out after 30 seconds.
<script runat="server">
Platform.Load("core", "1");
try {
var req = new Script.Util.HttpRequest("https://api.example.com/v1/offers");
req.method = "GET";
req.contentType = "application/json";
req.retries = 2;
req.continueOnError = true;
req.setHeader("Accept", "application/json");
var resp = req.send();
if (resp.statusCode == 200) {
var offers = Platform.Function.ParseJSON(String(resp.content));
Write("Offers found: " + offers.length);
} else {
Write("The offer service returned " + resp.statusCode);
}
} catch (e) {
Write("Something went wrong. Please try again later.");
}
</script> The response object gives you statusCode, content, contentType, headers and returnStatus. A returnStatus of 0 means the call worked. Negative values tell you it failed, for example because the URL was empty or no content came back.
💡 Keep secrets out of your code
Don't paste API keys or client secrets into a CloudPage or email. Anyone with access to Content Builder can read them. Store them somewhere protected, such as an encrypted data extension field or a key managed in Setup, and read them at run time.
Handle errors properly
Wrap every block that touches data or the network in try and catch. While you are building, it helps to print the full error so you can see what happened:
<script runat="server">
Platform.Load("core", "1");
try {
var rows = Platform.Function.LookupRows("Does_Not_Exist", "Id", "1");
} catch (e) {
Write(Platform.Function.Stringify(e));
}
</script> Remove that debug output before you go live. Customers should see a friendly message, not a stack trace. For CloudPages, a common pattern is to write errors into a logging data extension with the time, page name and message so you can review them later.
When to choose SSJS over AMPscript
Use AMPscript when:
- You need a few lookups or simple
IFlogic inside an email - You want the code to sit inline next to the content
Use SSJS when:
- You need loops over many rows, arrays or JSON
- You are calling an API or working with JSON responses
- You are writing CloudPage or Script activity logic that feels like real programming
You can mix both. A common approach is to do the heavy work in SSJS, store the result with Platform.Variable.SetValue, and print it with AMPscript in the content.
Summary
- Always use
<script runat="server"> - Use the Platform library in messages and load Core only for pages and Script activities
- Use
Lookup,LookupRowsandLookupOrderedRowsfor data extension reads - Use
HttpGetin messages andHttpRequestin pages, and remember the 30-second timeout - Wrap everything in
tryandcatch, with a safe default for every value