SuiteScript Overview
Understand NetSuite's JavaScript-based scripting platform, API versions, script types, governance model, and when to use code vs. configuration for business requirements.
What is SuiteScript?
SuiteScript is NetSuite's JavaScript-based API that enables developers to extend and customize the platform beyond its native capabilities. It provides programmatic access to NetSuite data, business logic, and user interface components.
- SuiteScript 1.0: Legacy API, still supported but no longer enhanced
- SuiteScript 2.0: Modern module-based API (recommended for all new development)
- SuiteScript 2.1: ES2019+ JavaScript features (async/await, arrow functions)
All new scripts should use SuiteScript 2.1 unless specific compatibility requirements exist.
When to Use SuiteScript
Before writing code, evaluate whether your requirement can be met through configuration. SuiteScript should be used when native features are insufficient.
| Requirement | Configuration Option | When SuiteScript Needed |
|---|---|---|
| Field validation | Mandatory fields, validation rules | Complex cross-field logic, external validation |
| Auto-populate fields | Sourcing, default values, formulas | Complex calculations, external lookups |
| Approval workflows | SuiteFlow workflows | Complex routing, external system integration |
| Scheduled tasks | Saved search alerts, reminders | Data processing, integration syncs |
| Custom UI | Custom forms, custom records | Custom pages, portlets, dynamic interfaces |
| Integrations | Native connectors (if available) | Custom APIs, bidirectional sync |
Always try configuration before coding. Native features are:
- Maintained by NetSuite (automatic upgrades)
- Better documented and supported
- No governance consumption
- Easier for administrators to maintain
Script Types Overview
| Script Type | Execution Context | Primary Use Cases |
|---|---|---|
| Client Script | Browser (user's machine) | Field validation, UI behavior, real-time calculations |
| User Event Script | Server (on record save/load) | Data validation, auto-population, transformations |
| Scheduled Script | Server (time-based) | Batch processing, data cleanup, integrations |
| Map/Reduce Script | Server (parallel processing) | Large data sets, complex transformations |
| Suitelet | Server (on-demand page) | Custom UI pages, wizards, internal tools |
| Restlet | Server (HTTP endpoint) | REST APIs, external integrations |
Governance Model
NetSuite uses a governance system to ensure fair resource allocation. Each script execution is allocated governance units, and API calls consume these units.
| Script Type | Governance Units |
|---|---|
| Client Script | 1,000 units |
| User Event Script | 1,000 units |
| Suitelet | 1,000 units |
| Restlet | 5,000 units |
| Scheduled Script | 10,000 units |
| Map/Reduce Script | 10,000 units per phase |
Common API Governance Costs
Operation Units
--------------------------------------------------
record.load() 10
record.save() 20
record.delete() 20
search.create().run() 10
search.lookupFields() 1
email.send() 20
http.request() 10
file.load() 10 Script Deployment
Every script requires two components: the Script record and the Script Deployment record.
Upload Script File
Upload .js file to File Cabinet (SuiteScripts folder recommended)
Create Script Record
Select script file, configure script parameters if needed
Create Deployment
Link script to record types/contexts, set execution roles
Set Status to Released
Change deployment status from Testing to Released for production
SuiteScript Readiness Checklist
User Event Scripts
Master server-side scripts that execute on record load, before save, and after saveโthe workhorses of NetSuite automation.
What Are User Event Scripts?
User Event scripts run on the server whenever a record is loaded, created, edited, or deleted. They execute automatically with record operationsโno user action required.
- beforeLoad: Runs before record is displayed (view/edit modes)
- beforeSubmit: Runs before record is saved to database
- afterSubmit: Runs after record is saved to database
Entry Point Details
beforeLoad
Executes before the record form is displayed. Use for UI modifications.
| Use Case | Example |
|---|---|
| Add custom buttons | Add "Generate PDF" button to sales order |
| Hide/show fields | Hide discount field for non-managers |
| Set field defaults | Default ship date to tomorrow |
| Add sublist columns | Add calculated column to item sublist |
beforeSubmit
Executes before the record is written to the database. Perfect for validation and data transformation.
| Use Case | Example |
|---|---|
| Data validation | Ensure margin meets minimum threshold |
| Data transformation | Uppercase customer name |
| Auto-populate fields | Set approval status based on amount |
| Block saves | Prevent duplicate PO numbers |
afterSubmit
Executes after the record is saved. Use for operations that require the saved record ID.
| Use Case | Example |
|---|---|
| Create related records | Create task when opportunity closes |
| Send notifications | Email customer when order ships |
| Update other records | Update customer status based on orders |
| External integrations | Push data to external CRM |
- Infinite loops: afterSubmit that edits the same record triggers another afterSubmit
- Blocking on external APIs: Slow beforeSubmit makes saves timeout
- Not handling null: Fields may be empty; always check before operations
- Ignoring oldRecord: Always compare to detect actual changes
- Always check context.type: Don't run validation on DELETE
- Handle errors gracefully: Use try/catch and log errors
- Minimize governance: Avoid record.load() when context.newRecord suffices
- Use afterSubmit for external calls: Don't block saves with slow API calls
User Event Script Checklist
Client Scripts
Browser-side scripts that enhance user experience with real-time validation, field manipulation, and dynamic form behavior.
Client Script Overview
Client Scripts execute in the user's browser when interacting with NetSuite forms. They provide immediate feedback, enforce business rules before submission, and create dynamic user experiences.
Client Script Entry Points
| Entry Point | Trigger | Common Uses |
|---|---|---|
pageInit | Form loads in browser | Initialize field values, hide/show fields |
fieldChanged | User changes field value | Dynamic sourcing, conditional logic |
postSourcing | After sourcing completes | Override sourced values |
sublistChanged | Line added/removed/changed | Sublist totals, line validation |
validateField | Before field value commits | Field-level validation |
saveRecord | Before form submits | Final validation, confirmation dialogs |
Client Script vs. User Event
- Only run in browser (not CSV import, web services, scripts)
- Can be bypassed by disabling JavaScript
- Governance limits apply (1,000 units)
- Cannot access server resources directly (use N/https for API calls)
Client Script Checklist
Scheduled Scripts
Time-based server scripts for batch processing, data maintenance, and scheduled integrations.
Scheduled Script Overview
Scheduled Scripts run on a defined schedule (daily, hourly, or specific times) to perform background processing without user interaction. They're ideal for batch operations, data cleanup, and scheduled integrations.
Common Use Cases
| Use Case | Schedule | Description |
|---|---|---|
| Invoice Generation | Daily, early morning | Create invoices from fulfilled orders |
| Data Cleanup | Weekly, off-hours | Archive old records, clean temp data |
| Integration Sync | Every 15-30 minutes | Pull/push data from external systems |
| Report Generation | Daily/Weekly | Generate and email reports |
| Reminder Emails | Daily | Send overdue invoice reminders |
- Monitor governance: Check remaining units and reschedule if needed
- Use script parameters: Allow configuration without code changes
- Log progress: Track processed records for debugging
- Handle restarts: Design for resumable processing
- Test timing: Verify schedule works across time zones
Scheduled Script Checklist
Map/Reduce Scripts
Parallel processing scripts for high-volume data operations with automatic governance management.
Map/Reduce Overview
Map/Reduce scripts process large data sets by breaking work into parallel stages. They automatically manage governance, handle failures, and scale across NetSuite's infrastructure.
The Four Stages
| Stage | Purpose | Concurrency |
|---|---|---|
| getInputData | Define data to process (search, query, array) | Single execution |
| map | Transform each input into key-value pairs | Parallel (up to 50) |
| reduce | Process grouped values by key | Parallel (up to 50) |
| summarize | Handle results, errors, generate summary | Single execution |
Scheduled vs. Map/Reduce
- Automatic parallelization: NetSuite manages concurrent execution
- Governance reset: Each map/reduce invocation gets fresh governance
- Error isolation: One failed record doesn't stop the entire job
- Built-in reporting: Summary stage provides execution statistics
Map/Reduce Script Checklist
Suitelets & Restlets
Build custom UI pages with Suitelets and RESTful APIs with Restlets for internal tools and external integrations.
Suitelet Overview
Suitelets are server-side scripts that generate custom UI pages. They can display forms, process user input, and perform any NetSuite operation.
Common Suitelet Use Cases
- Custom data entry wizards
- Bulk update tools
- Reporting dashboards
- Integration configuration pages
- Customer portals (with "Available Without Login")
Restlet Overview
Restlets provide RESTful API endpoints for external integrations. They handle HTTP GET, POST, PUT, and DELETE requests.
Restlet Authentication
| Method | Use Case | Security |
|---|---|---|
| Token-Based Auth (TBA) | Production integrations | OAuth 1.0 signature (recommended) |
| OAuth 2.0 | Modern integrations | Bearer token |
| NLAuth | Legacy/testing only | Not recommended for production |
Suitelet/Restlet Checklist
Workflow Automation
Design and implement business process automation using SuiteFlow workflows without coding.
Workflow Fundamentals
SuiteFlow is NetSuite's visual workflow builder that automates business processes without coding. Workflows consist of states, transitions, and actions that execute based on triggers and conditions.
Workflows vs SuiteScript
| Criteria | Workflows (SuiteFlow) | SuiteScript |
|---|---|---|
| Complexity | Simple to moderate logic | Complex, conditional logic |
| Maintenance | Business users can modify | Developers required |
| Debugging | Workflow history visible | Script logs and debugger |
| Performance | Lightweight, efficient | Full API access, more overhead |
| Best For | Approvals, notifications, field updates | Integrations, complex calculations |
Workflow Components
| Component | Description | Example |
|---|---|---|
| State | A step in the workflow process | Pending Approval, Manager Review, Approved |
| Transition | Movement from one state to another | Pending โ Manager Review (on submit) |
| Action | Work performed during a state | Send email, set field, create record |
| Condition | Logic that controls execution | Amount > 1000 AND Department = Sales |
Trigger Types
| Trigger On | When It Fires | Common Use |
|---|---|---|
| Before Record Load | Record opens in UI | Set defaults, show/hide fields |
| Before Record Submit | Before record saves | Validation, calculated fields |
| After Record Submit | After record saves | Send emails, create related records |
| Scheduled | On defined schedule | Periodic updates, reminders |
| Entry | When entering a state | State-specific actions |
Workflow Configuration Checklist
SuiteFlow Advanced
Master advanced workflow patterns including multi-level approvals, conditional routing, and workflow actions.
Approval Workflow Pattern
Approvals are the most common workflow use case. The standard pattern includes states for Draft, Pending Approval, Manager Review, Approved, and Rejected.
Multi-Level Approval Configuration
| Transition | Trigger | Condition |
|---|---|---|
| Draft โ Pending Approval | After Record Submit | Status = Pending Approval |
| Pending โ Manager Review | After Record Submit | Amount > $10,000 |
| Pending โ Approved | After Record Submit | Approved AND Amount โค $10,000 |
| Manager Review โ Approved | After Record Submit | Manager Approval = Approved |
| Any โ Rejected | After Record Submit | Approval Status = Rejected |
Workflow Actions
Field Actions
- Set Field Value: Update any field on the record
- Set Field Display Type: Make field hidden, disabled, or normal
- Set Field Mandatory: Make field required or optional
Communication Actions
- Send Email: Send email notifications with templates
- Add Note: Create note on record
Record Actions
- Create Record: Create new related record (task, event, custom)
- Transform Record: Convert to another record type
- Lock Record: Prevent editing of approved records
Advanced Actions
- Custom Action: Execute SuiteScript for complex logic
- Initiate Workflow: Trigger another workflow
- Return User Error: Show error message for validation
Use the Workflow History tab on records to see workflow execution details. Navigate to: Record > Workflow > View History. This shows states entered, actions executed, and any errors.
Advanced Workflow Checklist
Formula Fields & Expressions
Leverage formulas in saved searches, workflows, and custom fields for calculations without SuiteScript.
Formula Overview
Formulas provide a code-free way to create calculated values in NetSuite. They use SQL-like syntax and can be used in saved searches, workflow conditions, and custom fields.
Formula Locations
| Location | Syntax Type | Use Cases |
|---|---|---|
| Saved Search | Formula(Text/Numeric/Date/Currency) | Calculated columns, conditional formatting |
| Workflow Conditions | Workflow formula syntax | Transition conditions, action filters |
| Custom Fields | Default value formulas | Auto-calculated field values |
| Mass Update | Formula expressions | Calculated updates |
Common Formula Functions
Text Functions
CONCAT(field1, ' ', field2)โ Combine text valuesSUBSTR(field, start, length)โ Extract substringUPPER(field)/LOWER(field)โ Change caseNVL(field, 'default')โ Handle null values
Numeric Functions
ROUND(value, decimals)โ Round to decimal placesABS(value)โ Absolute valueNVL(field, 0)โ Replace null with zero
Date Functions
SYSDATEโ Current dateADD_MONTHS(date, n)โ Add months to dateTRUNC(date)โ Remove time portiondate2 - date1โ Days between dates
Conditional Logic
CASE WHEN condition THEN value1 ELSE value2 ENDDECODE(field, match1, result1, match2, result2, default)NVL2(field, if_not_null, if_null)
Formulas are calculated at runtime. Complex formulas on large result sets can slow searches significantly. For performance-critical reports, consider pre-calculating values via scheduled scripts and storing in custom fields.
