A ServiceNow Script Include is reusable server-side code, and there are four patterns worth knowing: a classless (on-demand) function, a class-based utility, a class that extends another, and a client-callable class for GlideAjax. Pick classless for one small function, a class for a group of related methods, extension to reuse a base class, and client-callable only when a browser script must reach the server.
This guide shows each pattern with working code, the naming rules that trip people up, and how scope and security settings change who can call your code.
Where Script Includes live
Open System Definition > Script Includes to create one. The records are stored in the sys_script_include table. The fields that matter most:
- Name: what callers use. For both classless and class-based patterns it must match the function or class name in the script.
- API Name: the scope-qualified name, such as
x_acme_app.AssetUtils. ServiceNow fills it in. - Accessible from: either "This application scope only" or "All application scopes".
- Client callable: allows GlideAjax calls. On Xanadu and later this checkbox is labelled Glide AJAX enabled, and a separate Sandbox enabled option controls calls from the script sandbox.
- Active: inactive Script Includes cannot be called.
Script Includes only load when a script uses them, so a large library does not slow down every transaction.
Pattern 1: Classless (on-demand) function
A classless Script Include defines one function. ServiceNow also calls this an on-demand Script Include. The Script Include name must exactly match the function name.
Name: getActiveGroupCount
function getActiveGroupCount(userId) {
var count = new GlideAggregate('sys_user_grmember');
count.addQuery('user', userId);
count.addQuery('group.active', true);
count.addAggregate('COUNT');
count.query();
return count.next() ? parseInt(count.getAggregate('COUNT'), 10) : 0;
}
Call it from any server-side script in the same scope by name:
var groups = getActiveGroupCount(gs.getUserID());
gs.info('Active groups for current user: ' + groups);
Classless works well for one small helper. It stops working well once you have several related functions, because each needs its own record and nothing groups them. It also cannot be called through GlideAjax.
Pattern 2: Class-based utility
This is the pattern ServiceNow generates when you create a new Script Include. It groups related methods under one name and lets you pass shared state through initialize.
Name: IncidentUtils
var IncidentUtils = Class.create();
IncidentUtils.prototype = {
initialize: function(maxRows) {
this.maxRows = maxRows || 100;
},
getOpenByGroup: function(groupId) {
var result = [];
var inc = new GlideRecord('incident');
inc.addActiveQuery();
inc.addQuery('assignment_group', groupId);
inc.orderByDesc('sys_created_on');
inc.setLimit(this.maxRows);
inc.query();
while (inc.next()) {
result.push(inc.getValue('number'));
}
return result;
},
isUnassigned: function(incGr) {
return incGr.assigned_to.nil();
},
type: 'IncidentUtils'
};
Call it with new:
var utils = new IncidentUtils(20);
var numbers = utils.getOpenByGroup('<assignment_group_sys_id>');
gs.info(numbers.join(', '));
Some rules that save debugging time:
- Keep the
typeproperty equal to the class name. Platform code and logging use it. - Pass records in as arguments rather than relying on a global
current. The method then works the same from a business rule, a flow script step or a background script. - Prefix internal helpers with an underscore, such as
_buildQuery. It is a convention, not enforcement, but reviewers will know not to call them.
The GlideRecord query performance guide covers how to keep the queries inside these methods fast. For ready-made examples of this pattern, see the user and group utilities and record query utility scripts.
Pattern 3: Extending a class
Use Object.extendsObject() when a new class should reuse another class's methods and override only some of them.
var MajorIncidentUtils = Class.create();
MajorIncidentUtils.prototype = Object.extendsObject(IncidentUtils, {
initialize: function(maxRows) {
IncidentUtils.prototype.initialize.call(this, maxRows);
this.priorityFilter = '1';
},
getOpenByGroup: function(groupId) {
var result = [];
var inc = new GlideRecord('incident');
inc.addActiveQuery();
inc.addQuery('assignment_group', groupId);
inc.addQuery('priority', this.priorityFilter);
inc.setLimit(this.maxRows);
inc.query();
while (inc.next()) {
result.push(inc.getValue('number'));
}
return result;
},
type: 'MajorIncidentUtils'
});
isUnassigned is inherited unchanged. If you override initialize, call the parent's version as shown, or the parent's setup never runs.
Extension is also how you customise many base system Script Includes safely. Several baseline classes ship as an empty ... subclass of an ...SNC class, and the empty class is the one meant for your changes. Editing the subclass instead of the original keeps your changes out of the way during upgrades. The upgrade skipped changes checklist explains why that matters.
Pattern 4: Client-callable for GlideAjax
When a client script needs server data, the Script Include must extend AbstractAjaxProcessor and have Client callable (or Glide AJAX enabled) selected. In a scoped application, extend global.AbstractAjaxProcessor.
var IncidentAjax = Class.create();
IncidentAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getOpenCount: function() {
var groupId = this.getParameter('sysparm_group_id');
if (!groupId || !/^[0-9a-f]{32}$/.test(groupId)) {
return JSON.stringify({ ok: false, error: 'invalid_group' });
}
if (!gs.hasRole('itil')) {
return JSON.stringify({ ok: false, error: 'not_allowed' });
}
var utils = new IncidentUtils(500);
return JSON.stringify({ ok: true, count: utils.getOpenByGroup(groupId).length });
},
type: 'IncidentAjax'
});
Notice that the Ajax class only validates input, checks the role and delegates to IncidentUtils. That split matters. Every public method on a client-callable class can be invoked by anyone who can send a request from a browser session, so keep it thin and keep server-only logic in a class that is not client callable.
The GlideAjax guide covers the client side: getXMLAnswer, parsing JSON and why to avoid getXMLWait. The GlideAjax multi-function utility script shows one class serving several related calls.
Calling across scopes
A Script Include in a scoped application is private by default. To share it:
- Set Accessible from to "All application scopes".
- Call it with the scope prefix:
new x_acme_app.AssetUtils(). - From a scoped app, call global code with
new global.IncidentUtils().
Calls across scopes are also subject to the target application's cross-scope privilege settings, so a call that works in one scope may need a privilege record in another. Keep scoped Script Includes private unless another application really needs them.
Choosing a pattern
| Need | Pattern | Called with |
|---|---|---|
| One small server function | Classless | myFunction(args) |
| Group of related server methods | Class-based | new MyUtils().method() |
| Reuse a class and change part of it | Extended class | new MySubUtils().method() |
| Client script needs server data | Client-callable, extends AbstractAjaxProcessor | new GlideAjax('MyAjax') |
| Value cached for the user's session | Class-based, called from a before query rule | See the session caching guide |
Common mistakes
- Name mismatch. If the record name differs from the class or function name, callers get "is not defined" errors. Rename both together.
- Client callable on a utility class. Selecting the checkbox on a class that does not extend
AbstractAjaxProcessordoes not make it work with GlideAjax. It only marks code as browser-facing that was never reviewed for that. - Business logic in business rules. Long scripts in business rules are hard to test and reuse. Move the logic into a Script Include and keep the rule to a single call.
- Global state. Each transaction gets a fresh instance of your class. Do not expect a variable set in one transaction to be there in the next; use the session or a table for that.
- Unbounded queries. A utility method that loops over every record on a large table will be slow everywhere it is reused. Add
setLimit()or a tighter query.
Checklist before you save
- The record name matches the class or function name.
- The
typeproperty matches the class name. - Accessible from is as narrow as possible.
- Client callable is selected only on classes that extend
AbstractAjaxProcessor. - Client-callable methods validate every parameter and check roles.
- Server-only logic lives in a class that is not client callable.
- Queries have limits and use indexed fields where possible.
Start with the class-based pattern for anything more than one function. It is easy to extend later, easy to test from Scripts - Background, and it keeps business rules, flows and Ajax classes small.