Handlebars is not defined” Error in NetSuite User Event Script

I’m fairly new to NetSuite, although I have done some maintenance work on existing SuiteScript code before. Currently, I’m working on a NetSuite User Event Script that uses Handlebars.js to generate a JSON payload from customer record data. However, I keep running into an error where the script logs “Handlebars is not defined”. Despite trying different approaches to load and initialize Handlebars, the issue persists.

Environment:
NetSuite API Version: 2.0
Script Type: User Event Script
Script Trigger: After Submit on Customer record creation and edit
What I’ve Tried:
Loading Handlebars.js:

I uploaded the handlebars.min.js file to the SuiteScripts/Libraries folder in NetSuite.
I’m loading the library using the file.load() function and then trying to execute it using Function().

Attempt to Initialize Handlebars:

var handlebarsFile = file.load({ id: 'SuiteScripts/Libraries/handlebars.min.js' });
var handlebarsLib = handlebarsFile.getContents();
var Handlebars = Function(handlebarsLib + 'return Handlebars;')();

Error Handling:

Despite this, I’m consistently seeing the error “Handlebars is not defined” in the script execution logs.

Script Details:
Here’s my script:

     /**
     * @NApiVersion 2.x
     * @NScriptType UserEventScript
     * @NModuleScope SameAccount
     */

    define(['N/record', 'N/log', 'N/file', 'N/https'], function(record, log, file, https) {

    function afterSubmit(context) {
        log.debug('Script Triggered', 'After Submit script triggered for customer record.');
        if (context.type !== context.UserEventType.CREATE && context.type !== context.UserEventType.EDIT) return;

        try {
            // Load the Handlebars.js library
            var handlebarsFile = file.load({
                id: 'SuiteScripts/Libraries/handlebars.min.js'
            });
            var handlebarsLib = handlebarsFile.getContents();

            // Execute the Handlebars library code in the current scope
            var Handlebars = Function(handlebarsLib + 'return Handlebars;')();

            log.debug('Handlebars Loaded', 'Successfully loaded Handlebars.');

            // Load the customer record
            var customer = record.load({
                type: record.Type.CUSTOMER,
                id: context.newRecord.id
            });

            log.debug('Customer Record Loaded', 'Customer ID: ' + customer.id);

            // Extract customer data
            var data = {
                email: customer.getValue('email') || '',
                firstname: customer.getValue('firstname') || '',
                lastname: customer.getValue('lastname') || '',
                username: customer.getValue('email') || '',
                phone: customer.getValue('phone') || '',
                role: customer.getText('pricelevel') || '',
                password: customer.getValue('custentity_pm_int_cust_pass') || '',
                billing: {},
                shipping: {}
            };

            // Extract address book data
            var addressCount = customer.getLineCount('addressbook');
            for (var i = 0; i < addressCount; i++) {
                var isBilling = customer.getSublistValue({
                    sublistId: 'addressbook',
                    fieldId: 'defaultbilling',
                    line: i
                });
                var isShipping = customer.getSublistValue({
                    sublistId: 'addressbook',
                    fieldId: 'defaultshipping',
                    line: i
                });

                var address = {
                    company: customer.getValue('companyname') || '',
                    firstname: customer.getValue('firstname') || '',
                    lastname: customer.getValue('lastname') || '',
                    addr1: customer.getSublistValue({
                        sublistId: 'addressbook',
                        fieldId: 'addr1',
                        line: i
                    }) || '',
                    addr2: customer.getSublistValue({
                        sublistId: 'addressbook',
                        fieldId: 'addr2',
                        line: i
                    }) || '',
                    city: customer.getSublistValue({
                        sublistId: 'addressbook',
                        fieldId: 'city',
                        line: i
                    }) || '',
                    state: customer.getSublistValue({
                        sublistId: 'addressbook',
                        fieldId: 'state',
                        line: i
                    }) || '',
                    zip: customer.getSublistValue({
                        sublistId: 'addressbook',
                        fieldId: 'zip',
                        line: i
                    }) || '',
                    country: customer.getSublistValue({
                        sublistId: 'addressbook',
                        fieldId: 'country',
                        line: i
                    }) || '',
                    phone: customer.getValue('phone') || ''
                };

                if (isBilling) {
                    data.billing = address;
                    log.debug('Billing Address Found', JSON.stringify(address));
                }

                if (isShipping) {
                    data.shipping = address;
                    log.debug('Shipping Address Found', JSON.stringify(address));
                }
            }

            // Handlebars template as a string
            var templateSource =
                '{' +
                '"data":{' +
                '"email": "{{record.email}}",' +
                '"first_name": "{{record.firstname}}",' +
                '"last_name": "{{record.lastname}}",' +

                '{{#if record.pricelevel}}' +
                '"role": [' +
                '"{{wooCommerceRole record.pricelevel.name}}",' +
                '{{#if record.custentity_pm_int_ws_credit_hold}} "credit_hold", {{/if}}' +
                '{{#if_eq record.terms.internalid "4"}} "cod" {{else}} "terms" {{/if_eq}}' +
                '],' +
                '{{/if}}' +
                '{{#if record.custentity_pm_int_update_ws_pass}}' +
                '"password": "{{record.custentity_pm_int_cust_pass}}",' +
                '{{/if}}' +
                '"username": "{{record.email}}",' +
                '"phone": "{{record.phone}}"' +
                '{{#if (gt record.addressbook.length 0)}}' +
                '{{#each record.addressbook}}' +
                '{{#if defaultbilling}}' +
                ',"billing": {' +
                '"company": "{{../record.companyname}}",' +
                '"first_name": "{{../record.firstname}}",' +
                '"last_name": "{{../record.lastname}}",' +
                '"address_1": "{{addr1}}",' +
                '"address_2": "{{addr2}}",' +
                '"city": "{{city}}",' +
                '"state": "{{state}}",' +
                '"postcode": "{{zip}}",' +
                '"country": "{{country}}",' +
                '"phone": "{{../record.phone}}"' +
                '}' +
                '{{/if}}' +
                '{{/each}}' +
                '{{#each record.addressbook}}' +
                '{{#if defaultshipping}}' +
                ',"shipping": {' +
                '"company": "{{../record.companyname}}",' +
                '"first_name": "{{../record.firstname}}",' +
                '"last_name": "{{../record.lastname}}",' +
                '"address_1": "{{addr1}}",' +
                '"address_2": "{{addr2}}",' +
                '"city": "{{city}}",' +
                '"state": "{{state}}",' +
                '"postcode": "{{zip}}",' +
                '"country": "{{country}}",' +
                '"phone": "{{../record.phone}}"' +
                '}' +
                '{{/if}}' +
                '{{/each}}' +
                '{{/if}}' +
                '}' +
                '}';

            // Compile the Handlebars template with the data
            var hbTemplate = Handlebars.compile(templateSource);
            var jsonData = hbTemplate({
                record: data
            });

            log.debug('Generated JSON', jsonData);

            // Send the JSON to the middleware endpoint
            var response = https.post({
                url: 'https://middleware.exampleserver.io/customer-sync',
                body: jsonData,
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            log.debug('Response from API', response.body);

        } catch (e) {
            log.error('Error in afterSubmit', e.message);
        }
    }

    return {
        afterSubmit: afterSubmit
    };
});

Original Handlebars Template:
Here’s the original Handlebars template I’m trying to work with:

{
"data": {
    "email": "{{record.email}}",
    "first_name": "{{record.firstname}}",
    "last_name": "{{record.lastname}}",

    {
        {
            #if record.pricelevel
        }
    }
    "role": [
            "{{wooCommerceRole record.pricelevel.name}}",
            {
                {
                    #if record.custentity_pm_int_ws_credit_hold
                }
            }
            "credit_hold",
            {
                {
                    /if}} {
                        {
                            #if_eq record.terms.internalid "4"
                        }
                    }
                    "cod" {
                        {
                            else
                        }
                    }
                    "terms" {
                        {
                            /if_eq}}
                        ], {
                            {
                                /if}} {
                                    {
                                        #if record.custentity_pm_int_update_ws_pass
                                    }
                                }
                                "password": "{{record.custentity_pm_int_cust_pass}}", {
                                    {
                                        /if}}
                                        "username": "{{record.email}}",
                                        "phone": "{{record.phone}}" {
                                            {
                                                #ifgreaterthan record.addressbook.length 0
                                            }
                                        } {
                                            {
                                                #each record.addressbook
                                            }
                                        } {
                                            {
                                                #if defaultbilling
                                            }
                                        }, "billing": {
                                            "company": "{{{../record.companyname}}}",
                                            "first_name": "{{../record.firstname}}",
                                            "last_name": "{{../record.lastname}}",
                                            "address_1": "{{addressbookaddress.addr1}}",
                                            "address_2": "{{addressbookaddress.addr2}}",
                                            "city": "{{addressbookaddress.city}}",
                                            "state": "{{addressbookaddress.state}}",
                                            "postcode": " {{addressbookaddress.zip}}",
                                            "country": "{{addressbookaddress.country.internalid}}",
                                            "phone": " {{{../record.phone}}}"
                                        }

                                        {
                                            {
                                                /if}} {
                                                    {
                                                        /each}}

                                                        {
                                                            {
                                                                #each record.addressbook
                                                            }
                                                        } {
                                                            {
                                                                #if defaultshipping
                                                            }
                                                        }, "shipping": {
                                                            "first_name": "{{../record.firstname}}",
                                                            "last_name": "{{../record.lastname}}",
                                                            "company": "{{{../record.companyname}}}",
                                                            "address_1": "{{addressbookaddress.addr1}}",
                                                            "address_2": "{{addressbookaddress.addr2}}",
                                                            "city": "{{addressbookaddress.city}}",
                                                            "state": "{{addressbookaddress.state}}",
                                                            "postcode": " {{addressbookaddress.zip}}",
                                                            "country": "{{addressbookaddress.country.internalid}}",
                                                            "phone": " {{{../record.phone}}}"
                                                        } {
                                                            {
                                                                /if}} {
                                                                    {
                                                                        /each}} {
                                                                            {
                                                                                /ifgreaterthan}}
                                                                            }
                                                                        }

What I Need Help With:

Correct Method for Loading Handlebars.js: Is there a more reliable way to load and initialize Handlebars in a NetSuite SuiteScript environment?

Alternatives: If Handlebars is not viable in SuiteScript, what alternatives would you suggest for dynamically generating JSON from a template?

Maybe I’m going about this the wrong way, so I’d really appreciate any guidance or suggestions you can offer.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật