What is g_user API in ServiceNow?

Unmasking the Current User: Your Guide to ServiceNow’s g_user API

Ever found yourself needing to know exactly who’s logged into ServiceNow right this moment, right from within a client-side script? Perhaps you want to personalize a form, show or hide specific fields based on someone’s role, or simply display a friendly “Welcome back!” message with their name. If so, you’re in the right place, because ServiceNow’s g_user API is your magic wand for exactly these scenarios.

This isn’t just another dry technical explanation. We’re going to dive deep into g_user, exploring its capabilities, how it fits into your daily development, and even some real-world tricks and traps. By the end, you’ll not only understand what g_user does but also how to wield its power effectively to create more dynamic, user-friendly, and intelligent ServiceNow applications.

What Exactly is g_user? Your Client-Side Window to User Data

Let’s kick things off with the basics. What is g_user? In a nutshell, g_user is a global JavaScript object that provides access to the currently logged-in user’s information and their roles directly on the client side. Think of it as a personal assistant available to your browser, holding all the immediate details about the person currently interacting with the ServiceNow page.

The beauty of g_user lies in its client-side accessibility. This means you can tap into this user data using JavaScript within client scripts, UI policies (via script sections), and even UI pages or widgets, without needing to make a trip back to the server. This translates to faster, more responsive user interfaces and a smoother experience for your end-users.

As our reference content (68) aptly puts it: “It’s used to get the current logged in user information and their roles at client side. and it can be accessed using g_user.” Simple, direct, and incredibly powerful.

Why g_user is Indispensable for Client-Side Scripting

You might be thinking, “Okay, it gets user info. So what?” Ah, but the “so what” is where the real fun begins! g_user isn’t just a fancy way to greet someone; it’s a cornerstone for building truly adaptive and intelligent user experiences in ServiceNow. Here’s why it’ll quickly become one of your best friends:

  • Personalization on the Fly: Imagine a form where certain fields automatically pre-populate with the current user’s name or department. Or a portal page that greets them by name, showing content relevant to *their* preferences.

  • Role-Based UI Adjustments: This is a big one. You can dynamically show, hide, make read-only, or even change the label of form fields based on whether the current user possesses a specific role. For instance, an “Approve” button might only appear for users with the approver_user role.

  • Enhanced User Experience: By tailoring the interface to the individual, you reduce clutter, streamline workflows, and make the system feel more intuitive. Less confusion means fewer support tickets and happier users.

  • Lightweight Checks: For many common scenarios, checking user roles or identity on the client side is perfectly sufficient and significantly faster than sending an AJAX call to the server for the same information. This is a performance win!

Essentially, any time you need to make a decision or display something different based on who is looking at the screen, g_user is your first port of call on the client side.

Peeking Behind the Curtain: Essential g_user Properties and Methods

Now, let’s roll up our sleeves and explore the specific pieces of information g_user offers. It comes loaded with a collection of handy properties (think variables that hold data) and methods (think functions that perform actions or retrieve formatted data).

Our reference content (69) gives us a great starting point, but we’ll expand on each of these, adding practical examples and real-world context.

Basic User Information: Names and Handles

These properties are straightforward and often used for display purposes or simple identification.

g_user.firstName

This property retrieves the first name of the currently logged-in user.


// Example: Get the user's first name
var userFirstName = g_user.firstName;
console.log("Hello, " + userFirstName + "!");
// Output might be: "Hello, John!"
    

Real-World Scenario: Imagine a custom greeting message on a portal widget. Instead of a generic “Welcome!”, you can make it personal: “Welcome, ” + g_user.firstName + “!”

g_user.lastName

Similar to firstName, this property gives you the last name of the current user.


// Example: Get the user's last name
var userLastName = g_user.lastName;
console.log("Your last name is: " + userLastName);
// Output might be: "Your last name is: Doe"
    

Real-World Scenario: If you need to construct a specific display format, or perhaps sort users by last name in a dynamically generated list (though for sorting, you’d likely fetch a list of users, not just the current one). It’s also useful when combining with firstName if you need explicit control over spacing or middle initials.

g_user.getFullName()

This is a method (notice the parentheses!) that returns the full display name of the user, typically in the format “First Name Last Name”. It’s generally preferred over concatenating firstName and lastName manually.


// Example: Get the user's full name
var userFullName = g_user.getFullName();
console.log("Your full name is: " + userFullName);
// Output might be: "Your full name is: John Doe"
    

Why prefer getFullName()? It handles nuances like middle names (if configured) or specific display formats set in the system more gracefully than simply joining firstName and lastName with a space. It also implicitly handles cases where a first or last name might be missing, returning the most appropriate full name string.

Real-World Scenario: Auto-populating a “Requested By” field on a custom form, displaying the current user’s full name in a read-only field, or for audit trails in client-side logging (though server-side logging is more robust).

g_user.userName

This property provides the user’s login ID – often the same as their email prefix or a unique identifier used for authentication.


// Example: Get the user's user name (login ID)
var userName = g_user.userName;
console.log("Your login ID is: " + userName);
// Output might be: "Your login ID is: jdoe" or "Your login ID is: john.doe"
    

Real-World Scenario: Useful for displaying the user’s actual login handle, especially in environments where full names aren’t always unique, or for integrating with external systems that rely on the login ID. You might use it in a client script that helps users remember their login if they forget it, or as part of a custom feedback form where users can report issues while logged in.

The All-Important User ID: Your Key to Uniqueness

While names are great for humans, systems need something truly unique and stable. That’s where the User ID comes in.

g_user.userID

This property returns the Sys ID (System ID) of the currently logged-in user. The Sys ID is a globally unique identifier (GUID) for every record in ServiceNow, including user records. It’s a 32-character hexadecimal string.


// Example: Get the current logged-in user's system ID
var userSysID = g_user.userID;
console.log("Your system ID is: " + userSysID);
// Output might be: "Your system ID is: 6816f79cc0a8016401c5a33be04be441" (as per reference 13)
    

Why is g_user.userID so crucial?

  • Uniqueness: Unlike names or usernames, Sys IDs are guaranteed to be unique across your entire ServiceNow instance. This prevents ambiguity.

  • Referencing Records: When you need to link the current user to other records (e.g., setting the “Assigned To” field on a task to the current user, or filtering a list of records created by the current user), you’ll almost always use the Sys ID.

  • Server-Side Interactions: When making GlideAjax calls to the server, passing the g_user.userID is the most reliable way for your server-side script to identify and query for the correct user record.

Interview Relevance: This is a very common interview question! Expect to be asked: “How do you get the current logged-in user’s system ID on the client side?” The answer, as you now know, is g_user.userID. They might also ask why it’s important, so be ready to explain its uniqueness and role in referencing records.

Real-World Scenario: A client script on an Incident form that, if the “Reported By” field is empty, automatically sets it to the current user’s Sys ID. This ensures data integrity and saves the user a step.

Beyond Basic Info: Roles and More

While the reference content focuses on basic user properties, g_user offers even more powerful methods, particularly for role management:

g_user.hasRole(roleName)

This method is a workhorse! It checks if the currently logged-in user has a specific role (including inherited roles). It returns true if the user has the role, and false otherwise.


// Example: Check if the user has the 'itil' role
if (g_user.hasRole('itil')) {
    console.log("You are an ITIL user!");
    g_form.setMandatory('assignment_group', true);
} else {
    console.log("You are not an ITIL user.");
}
    

Important Note on Inheritance: hasRole() considers role inheritance. If a user has the admin role, and the itil role is “contained” within admin (meaning an admin implicitly has itil), then g_user.hasRole('itil') would return true for an admin. This is usually the desired behavior.

Real-World Scenario: Dynamically displaying an “Admin Tools” section on a form or portal page only if g_user.hasRole('admin'). Or making specific fields read-only for non-ITIL users on an Incident form.

g_user.hasRoleExactly(roleName)

This method is similar to hasRole() but with a crucial difference: it only returns true if the role is directly assigned to the user, not if it’s inherited. This is less commonly used but vital when you need strict role checks.


// Example: Check if the user has the 'admin' role directly
if (g_user.hasRoleExactly('admin')) {
    console.log("You are explicitly an admin!");
} else {
    console.log("You do not have the admin role directly assigned.");
}
    

Real-World Scenario: A very specific application might require that only users explicitly granted a certain role (and not just inheriting it from a higher-level role) can perform a particular client-side action. This is more niche but good to know it exists.

g_user.hasRoleFromList(roleList)

This handy method checks if the user has any of the roles specified in a comma-separated list. It returns true if the user has at least one of the roles in the list, and false otherwise.


// Example: Check if the user has either 'itil' or 'hr_admin' role
if (g_user.hasRoleFromList('itil,hr_admin')) {
    console.log("You are either an ITIL or HR Admin user.");
    g_form.setReadOnly('confidential_info', false);
} else {
    console.log("Access to confidential info restricted.");
    g_form.setReadOnly('confidential_info', true);
}
    

Real-World Scenario: Controlling access to certain sensitive fields based on a group of roles that are allowed to see or edit them, rather than writing multiple if (g_user.hasRole('role1') || g_user.hasRole('role2')) statements.

Putting g_user to Work: Real-World Scenarios

Let’s make this even more tangible with some practical applications that you might encounter or implement in your ServiceNow journey.

Scenario 1: Auto-populating Fields for Efficiency

Imagine an Incident form where the “Caller” field is initially empty, but for the majority of cases, the person filling out the form is the caller. You can use g_user to pre-populate this, saving clicks and improving user experience.


// Client Script: onLoad on the Incident form
function onLoad() {
    // Only pre-populate if the 'caller_id' field is currently empty
    if (g_form.getValue('caller_id') == '') {
        // Set the 'caller_id' field to the current user's Sys ID
        g_form.setValue('caller_id', g_user.userID);
        // Display their name in the reference field
        g_form.setDisplayValue('caller_id', g_user.getFullName());
    }
}
    

This simple script checks if the ‘Caller’ field is blank and, if so, automatically fills it with the current user’s details. Handy!

Scenario 2: Dynamic UI Adjustments Based on Roles

Let’s say you have a custom application with some advanced configuration options that should only be visible to users with a specific administrative role (e.g., ‘my_app_admin’).


// Client Script: onLoad on your custom form
function onLoad() {
    // Check if the current user has the 'my_app_admin' role
    if (g_user.hasRole('my_app_admin')) {
        // If they do, show the 'advanced_config_section'
        g_form.setSectionDisplay('advanced_config_section', true);
    } else {
        // Otherwise, hide it
        g_form.setSectionDisplay('advanced_config_section', false);
    }
}
    

This allows you to provide a clean, uncluttered interface for regular users while still offering powerful options to administrators, all controlled dynamically.

Scenario 3: Custom Messages or Warnings

You might want to display a personalized warning or information message based on a user’s role or status.


// Client Script: onLoad or onChange on any form
function onLoad() {
    if (g_user.hasRole('contractor')) {
        g_form.addInfoMessage("As a contractor, please ensure all sensitive data is handled with care, " + g_user.firstName + ".");
    } else if (g_user.hasRole('itil')) {
        g_form.addInfoMessage("Welcome back, " + g_user.getFullName() + "! Remember to check the critical incident queue.");
    }
}
    

This adds a touch of personality and targeted communication to the user experience.

g_user’s Place in the Client-Side Pantheon: A Member of a Powerful Family

g_user doesn’t work in isolation. It’s part of a powerful ecosystem of client-side APIs that ServiceNow provides to empower front-end development. Our reference content (129) gives us a list of some of these:

  • GlideUser (that’s our g_user!)
  • GlideForm (g_form)
  • GlideAjax
  • GlideModal
  • GlideModalForm
  • GlideDialogWindow
  • GlideList
  • GlideNavigation
  • GlideScratchpad

Notice how many of our examples combine g_user with g_form? That’s because they frequently work hand-in-hand. You use g_user to get information about who is interacting with the system, and then you use g_form to manipulate what they see or do on the form based on that information.

Similarly, you might use g_user.userID as a parameter in a GlideAjax call to send the current user’s ID to a server-side script, allowing the server to perform queries or actions specific to that user.

Understanding g_user isn’t just about mastering one API; it’s about seeing how it integrates and enhances the capabilities of the entire client-side framework, making your solutions more robust and dynamic.

Troubleshooting Your g_user Adventures

Even the most seasoned developers hit snags. Here are a few common issues you might encounter with g_user and how to troubleshoot them:

Issue 1: “My role check isn’t working!”

You’ve written if (g_user.hasRole('itil')), but it’s always returning false, even for ITIL users. What gives?

  • Case Sensitivity: Role names are case-sensitive! 'itil' is different from 'ITIL'. Double-check the exact spelling and casing of the role in the User Administration > Roles module.

  • Typos: A common culprit. A simple misspelling like 'itill' will obviously fail.

  • hasRole() vs. hasRoleExactly(): Remember the distinction. If you used hasRoleExactly('admin') and the user inherits admin via a group, it will return false. Most of the time, hasRole() is what you need.

  • Role Hierarchy/Containment: If you’re checking for a base role (e.g., 'catalog_manager') and the user only has a more encompassing role that includes it (e.g., 'admin'), hasRole() *should* work. If it’s not, verify the role hierarchy configuration. This is less a g_user issue and more a role setup issue.

Issue 2: “g_user is undefined!”

This is rare on standard ServiceNow forms but can occur in specific contexts, such as non-authenticated pages or very custom UI pages/widgets where the global objects might not be fully loaded or available in the script’s execution context.

  • Context Check: Ensure your script is running in an environment where g_user is expected to be present (e.g., a standard client script on a form, not a public page where no one is logged in).

  • Timing: While usually not an issue with g_user, sometimes scripts can execute before the entire page’s client-side objects are fully initialized. If you’re using very custom DOM manipulation or timing-sensitive logic, this could theoretically be a factor. For standard client scripts (onLoad, onChange, onSubmit), g_user is reliably available.

Debugging with console.log()

Your best friend for troubleshooting client-side scripts is the browser’s developer console. You can inspect the entire g_user object to see exactly what data it contains:


// Place this at the beginning of your client script to see all g_user properties
console.log(g_user);
    

This will output the g_user object, allowing you to expand it and see all its properties and their current values, which is invaluable for identifying discrepancies or unexpected values.

Nailing the Interview: g_user Questions You Might Face

Mastering g_user is not just for coding; it’s a fundamental concept that comes up frequently in ServiceNow developer interviews. Here’s a rundown of common questions and how you can confidently answer them:

  • “What is the g_user API used for in ServiceNow?”
    Answer: “The g_user API is a global JavaScript object available on the client side. It’s used to retrieve information about the currently logged-in user, including their name, username, system ID, and roles. This data allows for client-side personalization, dynamic UI adjustments, and role-based logic.”

  • “Name some common methods or properties of the g_user API.”
    Answer: “Some essential properties include g_user.firstName, g_user.lastName, g_user.userName, and crucially, g_user.userID (which gives the user’s Sys ID). For methods, g_user.getFullName() is useful for getting the user’s full display name, and g_user.hasRole('role_name') is vital for checking user roles.”

  • “How do you get the current logged-in user’s system ID on the client side?”
    Answer: “You use g_user.userID. This returns the 32-character globally unique identifier (Sys ID) for the user record, which is essential for referencing the user in other records or server-side queries.”

  • “How would you check if the current user has the ‘itil’ role client-side, and why is this useful?”
    Answer: “You’d use g_user.hasRole('itil'). This is incredibly useful for dynamically controlling form elements – for example, showing or hiding specific fields, making them read-only, or even displaying targeted messages, all based on whether the user has the ‘itil’ role, improving user experience and data integrity.”

  • “What’s the difference between g_user.hasRole() and g_user.hasRoleExactly()?”
    Answer:g_user.hasRole() checks if the user has a specific role, including roles inherited through groups or other roles. g_user.hasRoleExactly(), on the other hand, only returns true if the role is directly assigned to the user, ignoring any inherited roles. Typically, hasRole() is preferred unless a very strict direct role assignment check is needed.”

  • “Can you give a real-world scenario where you’d use g_user?”
    Answer: “Certainly. On an Incident form, if the ‘Caller’ field is empty, I’d use an onLoad client script to automatically populate it with the current user’s Sys ID (g_user.userID) and display their full name (g_user.getFullName()). This saves the user time and ensures the field is correctly filled by default.”

Best Practices and Performance Considerations

While g_user is powerful, keep these best practices in mind to write efficient and secure code:

  • Client-Side for UX, Server-Side for Security: Never rely solely on client-side role checks (or any client-side validation) for critical security decisions or data integrity. Client-side scripts can be bypassed. Always implement server-side validation (e.g., Business Rules, Access Control Lists) for operations that involve creating, updating, or deleting sensitive data, or granting access to critical information. Client-side checks are for enhancing UX and guiding users.

  • Cache Values if Repeatedly Used: If your script accesses the same g_user property multiple times, it’s a good practice to store it in a local variable for minor performance gains and cleaner code. For example: var currentUserSysID = g_user.userID;

  • Keep Scripts Lean: While g_user operations are fast, extensive or complex client scripts can still impact page load times. Be mindful of the number and complexity of your client scripts and UI policies.

  • Validate Input: Even though g_user provides current user data, always validate any user-entered data before processing, regardless of who the user is.

Embrace the Power of g_user!

Hopefully, this deep dive has demystified the g_user API for you. It’s not just a collection of properties; it’s a fundamental tool in your ServiceNow development toolkit for crafting more intelligent, responsive, and user-centric applications. From personalizing greetings to dynamically controlling complex form layouts based on roles, g_user empowers you to create experiences that truly resonate with your users.

So, go forth and experiment! Open your browser’s developer console, type console.log(g_user);, and explore its contents. Practice using hasRole() and its siblings. The more you play with g_user, the more natural and intuitive it will become, making your ServiceNow solutions shine.

Happy scripting!

Scroll to Top