Code Snippets

A collection of useful code snippets and components.


Showing 10 of 10 snippets
SSJS

Secure a CloudPage for logged in users

Implements a secure OAuth 2.0 Authorization Code flow to protect a Cloud Page. Requires an Installed Package with a "Web App" API Integration in SFMC.Handles token validation, secure cookie sessions, and optional client-side token handoff.

HTML
<script runat="server">
    Platform.Load("core", "1");

    // -----------------------------------------------------------------------
    // PREREQUISITES & SETUP:
    // 1. Setup → Installed Packages → New
    // 2. Add Component → API Integration → Integration Type: Web App
    // 3. Set "Redirect URI" to EXACT CloudPage URL (no mismatched slashes)
    // 4. Anyone with access to the Installed Package can generate tokens
    // -----------------------------------------------------------------------

    // -----------------------------------------------------------------------
    // 1. CONFIGURATION
    // -----------------------------------------------------------------------
    var config = {
        clientId: "YOUR_CLIENT_ID",
        clientSecret: "YOUR_CLIENT_SECRET",
        subdomain: "YOUR_SUBDOMAIN",            // e.g. mc-xxxxxx-xxxx
        redirectUri: "YOUR_CLOUDPAGE_LINK",     // Must match installed package exactly
        cookieName: "App_Auth_Token",

        // SECURITY SETTINGS
        exposeTokenToClient: false,     // Set to true only if client JS must call SFMC APIs
        validateTokenOnLoad: true       // Validate token on page load (safer, adds latency)
    };

    // Auto-constructed OAuth endpoints
    config.authEndpoint     = "https://" + config.subdomain + ".auth.marketingcloudapis.com/v2/authorize";
    config.tokenEndpoint    = "https://" + config.subdomain + ".auth.marketingcloudapis.com/v2/token";
    config.userInfoEndpoint = "https://" + config.subdomain + ".auth.marketingcloudapis.com/v2/userinfo";

    // -----------------------------------------------------------------------
    // 2. CHECK FOR EXISTING SESSION
    // -----------------------------------------------------------------------
    var accessToken = Platform.Request.GetCookieValue(config.cookieName);
    var authCode    = Platform.Request.GetQueryStringParameter("code");

    // -----------------------------------------------------------------------
    // 2.5 VALIDATE EXISTING TOKEN
    // -----------------------------------------------------------------------
    if (accessToken && config.validateTokenOnLoad) {

        try {
            var validateReq = new Script.Util.HttpRequest(config.userInfoEndpoint);
            validateReq.emptyContentHandling = 0;
            validateReq.retries = 2;
            validateReq.continueOnError = true;
            validateReq.contentType = "application/json";
            validateReq.setHeader("Authorization", "Bearer " + accessToken);
            validateReq.method = "GET";

            var validateResp = validateReq.send();

            // Invalid token → regenerate
            if (validateResp.statusCode == 401) {
                accessToken = null;

                // Clear cookie
                Platform.Response.SetCookie(
                    config.cookieName,
                    "",
                    new Date("1970-01-01")
                );
            }
        } catch (e) {
            // Any error → re-authenticate
            accessToken = null;
        }
    }

    // -----------------------------------------------------------------------
    // SCENARIO A: NO TOKEN + NO CODE → Initiate OAuth Login
    // -----------------------------------------------------------------------
    if (!accessToken && !authCode) {
        var authUrl =
            config.authEndpoint +
            "?response_type=code" +
            "&client_id=" + config.clientId +
            "&redirect_uri=" + config.redirectUri;

        Platform.Response.Redirect(authUrl);
    }

    // -----------------------------------------------------------------------
    // SCENARIO B: CODE PRESENT → Exchange for Token
    // -----------------------------------------------------------------------
    if (!accessToken && authCode) {

        var payload = {
            grant_type: "authorization_code",
            code: authCode,
            client_id: config.clientId,
            client_secret: config.clientSecret,
            redirect_uri: config.redirectUri
        };

        try {
            var result = HTTP.Post(
                config.tokenEndpoint,
                "application/json",
                Stringify(payload)
            );

            if (result.StatusCode == 200) {

                var response = Platform.Function.ParseJSON(result.Response[0]);

                // Set cookie (expire in 20 minutes)
                Platform.Response.SetCookie(
                    config.cookieName,
                    response.access_token,
                    new Date(new Date().getTime() + (1000 * 60 * 20))
                );

                // Clear query string
                Platform.Response.Redirect(config.redirectUri);

            } else {
                Write("Error exchanging token: " + result.Response[0]);
            }
        } catch (e) {
            Write("Critical Auth Error: " + Stringify(e));
        }
    }

    // -----------------------------------------------------------------------
    // SCENARIO C: TOKEN OK → Render page & optionally expose to client
    // -----------------------------------------------------------------------
    if (accessToken && config.exposeTokenToClient) {
        Platform.Variable.SetValue("@accessToken", accessToken);
    }

</script>


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Protected Page</title>

    <!--
        CRITICAL NOTE:
        If a user is seeing this HTML, they are authenticated.
        Expired tokens are handled server-side BEFORE this HTML renders.
    -->

    <style>
        body {
            font-family: sans-serif;
            padding: 40px;
            text-align: center;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
        }
    </style>
</head>

<body>

    <div class="container">
        <h1>🔒 Secure Access Granted</h1>
        <p>This content is only visible to authenticated users.</p>
    </div>

    <!-- Optional: Token Handoff to Client -->
    %%[ IF NOT EMPTY(@accessToken) THEN ]%%
        <input type="hidden" id="sfmc-token" value="%%=v(@accessToken)=%%" />
    %%[ ENDIF ]%%

    <script>
        // CLIENT-SIDE SAFETY NET
        const tokenInput = document.getElementById("sfmc-token");
        const token = tokenInput ? tokenInput.value : null;

        // If SSJS says a token exists but JS doesn’t see it → warning
        if (!token && "%%=v(@accessToken)=%%" !== "") {
            console.warn("Token handoff failed.");
        }
    </script>

</body>
</html>
30 copies
AI Prompts

AI Prompt for better SFMC queries

Write better sfmc specific queries using this prompt in your favourite AI tool

Text
```plain text
SFMC SQL Query InstructionsOverview:
SFMC SQL is based on Microsoft SQL Server (T-SQL)
Only SELECT queries are allowed. Target Data Extensions (DEs) are configured in the UI
Query runs against Data Extensions and Data Views (e.g., _Sent, _Open)
Query Activities output to a DE in Overwrite, Append, or Update modes
Max runtime: 30 min; complex joins can timeout
Supported Features:Query Structure:
SELECT with columns or *. Use aliases to match target DE fields
WHERE, DISTINCT, TOP (n) with ORDER BY
Joins: INNER, LEFT/RIGHT, FULL OUTER joins supported (limit joins for performance)
UNION / UNION ALL supported (same column count)
Subqueries allowed in SELECT, FROM, WHERE
GROUP BY, HAVING supported with aggregates
CASE WHEN ... END and IIF(condition, true, false) supported
Window functions: ROW_NUMBER(), RANK(), NTILE() allowed (use in subqueries)
Functions:
String: LEN, LOWER/UPPER, SUBSTRING, CHARINDEX, LEFT/RIGHT, CONCAT, ISNULL, COALESCE
Date: GETDATE (CST), GETUTCDATE, DATEADD, DATEDIFF, DATEPART, EOMONTH, CONVERT(DATE, x)
Numeric: ABS, ROUND, FLOOR, % operator
Casting: CAST and CONVERT (prefer CONVERT for formatting)
Writing to Target DE:
Target DE cannot be in the FROM clause
Output columns must match target DE fields and types
Write modes: Overwrite (truncate+insert), Append (insert only), Update (upsert by PK)
```
77 copies
SQL

Extract URL Parameters in SQL

Extract URL parameters from URLs in SFMC. Useful for querying the _Click data view or other Data Extensions that contain Link data you want to use.

SQL
SELECT
    c.LinkContent,
    x.CampaignName
FROM _Click c

CROSS APPLY (
    SELECT CHARINDEX('utm_campaign=', c.LinkContent) AS StartPos
) pos

CROSS APPLY (
    SELECT
        CASE
            WHEN pos.StartPos = 0 THEN NULL
            ELSE SUBSTRING(
                c.LinkContent,
                pos.StartPos + 13, -- Match the length of your URL parameter, including the = sign
                CASE
                    WHEN CHARINDEX('&', c.LinkContent, pos.StartPos) > 0
                    THEN CHARINDEX('&', c.LinkContent, pos.StartPos) - (pos.StartPos + 13) -- match lenght here too
                    ELSE LEN(c.LinkContent)
                END
            )
        END AS CampaignName
) x

WHERE
    c.EventDate > DATEADD(day, -3, GETDATE()) -- dont query the entire click data view, work in batches
    AND x.CampaignName IS NOT NULL -- only return rows where the extraction was succesful, remove if you need to return all rows with nulls
19 copies

Get the latest snippets

Join 2,000+ engineers receiving new marketing engineering patterns and snippets every month.

AMPScript

EmailPreview AMPScript Function

Undocumented AMPScript function that can run in CloudPages to generate email previews. Useful for automating or expediting email QA process or building other tools in CloudPages.

JavaScript
%%=EmailPreview("Data Extension Name", "Custom Object Key", "Email Object ID")=%%
35 copies
SSJS

Object-Oriented SSJS Pattern (Logger)

A reusable Logger class using the Prototype pattern. It standardizes how you write logs to a Data Extension, handling timestamps, error parsing, and severity levels automatically. use the prototype approach to define logic that belongs to an object (A function in this case).

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

    /**
     * 1. THE CONSTRUCTOR
     * Sets up the configuration for this specific logger instance.
     * @param {string} deName - The External Key of the Log DE
     * @param {string} component - The name of the script running (e.g., "MyCloudPage")
     */
    function Logger(deName, component) {
        this.de = deName;
        this.source = component;
        this.debugMode = true; // Toggle to false to suppress "Info" logs in prod
    }

    /**
     * 2. THE METHODS
     * Shared logic to handle writing to the database.
     */

    // Method: Log generic info (Standard operational logs)
    Logger.prototype.info = function(message) {
        if (this.debugMode) {
            this._write("INFO", message);
        }
    };

    // Method: Log a warning (Something weird happened, but didn't crash)
    Logger.prototype.warning = function(message) {
        this._write("WARNING", message);
    };

    // Method: Log an error (Critical failure)
    // Smartly handles JS Error objects vs. strings
    Logger.prototype.error = function(error) {
        var msg = error;
        if (typeof error === "object" && error.message) {
            msg = error.message + " | " + Platform.Function.Stringify(error);
        }
        this._write("ERROR", msg);
    };

    /**
     * INTERNAL METHOD (The Worker)
     * Handles the actual InsertData call. 
     * Prefixed with _ to show it's "private" (convention only).
     */
    Logger.prototype._write = function(level, message) {
        try {
            var cleanMsg;
            
            // 1. Robust Stringification Logic
            // If it is NOT a string (e.g. Object, Array, Number, or weird SFMC System Object),
            // force it into JSON format. This fixes the "System.Collections..." log issue.
            if (typeof message !== 'string') {
                try {
                    cleanMsg = Platform.Function.Stringify(message);
                } catch (e2) {
                    // Fallback if Stringify fails (rare)
                    cleanMsg = String(message); 
                }
            } else {
                cleanMsg = message;
            }
            
            // 2. Write to DE
            Platform.Function.InsertData(
                this.de,
                ["Source", "Level", "Message", "LogDate"],
                [this.source, level, cleanMsg, new Date()]
            );
        } catch (e) {
            // Failsafe: If logging fails, print to screen so we know
            Write("<br>LOGGING FAILED: " + e.message);
        }
    };

    // -----------------------------------------
    // 3. USAGE (The "Clean" Code)
    // -----------------------------------------
    
    // Initialize once at the top of your script
    var log = new Logger("LOGGER_DE_EXTERNAL_KEY", "Welcome_Journey_Script");

    try {
        log.info("Script Started");

        var subscriberID = "12345";
      
        var err = 10 / 0;
        
        // Simulate Logic
        if (subscriberID) {
            log.info("Processing subscriber: " + subscriberID);
        } else {
            log.warning("No SubscriberID found in context.");
        }

        // Simulate Logging an Object 
        var contextData = { "Status": "Active", "Points": 500 };
        log.info(contextData);

    } catch (e) {
        // Look how clean this is compared to writing InsertData here
        log.error(e);
    }
</script>
6 copies
AMPScript

LookupOrderedRows in AMPScript: Retrieve and Sort Related Data

An optimized AMPScript pattern using LookupOrderedRows to retrieve, sort, and limit related records (like transaction history) from a Data Extension. This prevents OMM timeouts by handling sorting at the database level rather than the script level.

JavaScript
%%[
    /* Retrieve top 3 rows ordered by OrderDate Descending */
    SET @rows = LookupOrderedRows("Orders_DE", 3, "OrderDate Desc", "SubscriberKey", _subscriberKey)
    SET @rowCount = RowCount(@rows)

    IF @rowCount > 0 THEN
        FOR @i = 1 TO @rowCount DO
            SET @row = Row(@rows, @i)
            SET @ProductName = Field(@row, "ProductName")
            SET @OrderDate = Field(@row, "OrderDate")
            SET @OrderTotal = Field(@row, "Total")
]%%
    <div style="border-bottom: 1px solid #eee; padding: 10px;">
        <p><strong>Product:</strong> %%=v(@ProductName)=%%</p>
        <p>Date: %%=Format(@OrderDate, "MMM dd, yyyy")=%% | Total: $%%=FormatNumber(@OrderTotal, "N2")=%%</p>
    </div>
%%[ 
        NEXT @i 
    ELSE 
]%%
    <div style="padding: 10px;">
        <p>You have no recent orders. <a href="https://site.com/shop">Start shopping</a>.</p>
    </div>
%%[ ENDIF ]%%
4 copies
SSJS

Trigger an Automation in SSJS

Trigger an automation to run programmatically. Great for chaining automation runs (where one automation calls another) or for running in cloudpages.

SQL
<script runat="server">
    Platform.Load("core", "1.1.1");

    /**
     * Starts an Automation immediately if it is currently "Ready".
     * @param {string} customerKey - The External Key of the Automation
     * @returns {string} - Status message (e.g., "Started", "Running", "Error")
     */
    function startAutomation(customerKey) {
        
        // 1. Setup the Retrieve Request to find the Automation
        var rr = Platform.Function.CreateObject("RetrieveRequest");
        Platform.Function.SetObjectProperty(rr, "ObjectType", "Automation");
        Platform.Function.AddObjectArrayItem(rr, "Properties", "ProgramID");
        Platform.Function.AddObjectArrayItem(rr, "Properties", "CustomerKey");
        Platform.Function.AddObjectArrayItem(rr, "Properties", "Status");
        
        // 2. Filter by Customer Key
        var sfp = Platform.Function.CreateObject("SimpleFilterPart");
        Platform.Function.SetObjectProperty(sfp, "Property", "CustomerKey");
        Platform.Function.SetObjectProperty(sfp, "SimpleOperator", "equals");
        Platform.Function.AddObjectArrayItem(sfp, "Value", customerKey);
        Platform.Function.SetObjectProperty(rr, "Filter", sfp);
        
        // 3. Execute Retrieve
        var statusOut = [0, 0, 0];
        var results = Platform.Function.InvokeRetrieve(rr, statusOut);

        if (results && results.length > 0) {
            var objectID = results[0]["ObjectID"];
            var currentStatus = results[0]["Status"];

            // Status 2 = Ready
            if (currentStatus == 2) {
                
                // 4. Automation is Ready -> Perform "Start"
                var obj = Platform.Function.CreateObject("Automation");
                Platform.Function.SetObjectProperty(obj, "ObjectID", objectID);
                
                var po = Platform.Function.CreateObject("PerformOptions");
                var performResult = [0, 0, 0];
                var performStatus = Platform.Function.InvokePerform(obj, "start", performResult, po);
                
                return performStatus == "OK" ? "Started" : "Perform Failed: " + performStatus;
                
            } else if (currentStatus == 3) {
                return "Skipped: Automation is already running.";
            } else {
                return "Skipped: Automation status is " + currentStatus + " (Not Ready).";
            }
        } else {
            return "Error: Automation not found.";
        }
    }

    // --- Usage Example ---
    try {
        var result = startAutomation("AUTOMATION_EXTERNAL_KEY");
        Write("Result: " + result);
    } catch (e) {
        Write("Critical Error: " + Stringify(e));
    }
</script>
14 copies
SQL

SQL: Find Automations that take too long to run

Find Automation runs that took longer than an hour to run in the last week. Use as a starting point to find opportunities to optimize or split automations to improve performance.

SQL
SELECT TOP 900000000000 -- needed for ORDER BY
    AutomationName,
    AutomationCustomerKey,
    AutomationInstanceStatus,
    AutomationInstanceStartTime_UTC,
    AutomationInstanceEndTime_UTC,
   
    DATEDIFF(minute, AutomationInstanceStartTime_UTC, AutomationInstanceEndTime_UTC) AS DurationMinutes
FROM _AutomationInstance
WHERE
 
    AutomationInstanceStartTime_UTC >= DATEADD(day, -7, GETUTCDATE()) -- Adjust lookback window as required
   
    AND DATEDIFF(minute, AutomationInstanceStartTime_UTC, AutomationInstanceEndTime_UTC) > 60 -- adjust minutes as required
ORDER BY 
    DurationMinutes DESC
13 copies
AMPScript

ContentBlockByKey

A modular architecture pattern using ContentBlockByKey to load reusable content assets dynamically based on subscriber context, facilitating easier maintenance than ContentBlockByID.

JavaScript
%%[
    /* Define context variables to be used inside the block */
    SET @CampaignName = "Winter_Sale_2025"
    
    /* Dynamically load content based on a logic variable */
    SET @footerKey = Concat("Footer_", @UserRegion) 
    
    /* Fallback if region is empty */
    IF Empty(@UserRegion) THEN SET @footerKey = "Footer_Global" ENDIF
    
    SET @content = ContentBlockByKey(@footerKey)
]%%
<div class="footer-wrapper">
    %%=v(@content)=%%
</div>
4 copies
AMPScript

ClaimRow in AMPScript: Unique Coupon Distribution Code

A concurrency-safe AMPScript solution using ClaimRow to assign unique codes to subscribers. Handles row locking to prevent double-claiming during high-volume sends.

JavaScript
%%[
    /* Claim a row from Coupons_DE where IsClaimed is false */
    /* Locking based on CouponID column (or other unique index) */
    SET @couponRow = ClaimRow("Coupons_DE", "IsClaimed", "SubscriberKey", _subscriberKey)

    IF NOT Empty(@couponRow) THEN
        SET @couponCode = Field(@couponRow, "Code")
    ELSE
        RaiseError("No coupons available", true)
    ENDIF
]%%
<div style="border: 1px dashed #000; padding: 20px; text-align: center;">
    <p>Your exclusive code:</p>
    <h2 style="font-family: monospace;">%%=v(@couponCode)=%%</h2>
</div>
3 copies