React in ServiceNow: how to access the data
When you build ServiceNow applications with React the first thing you want to have is access to ServiceNow data.
The way how you get access differs for development and production environments, but it is straightforward:
Development environment setup
Development environment setup is about establishing communication with your ServiceNow instance while building your application locally.
Here are just a few steps to follow. I prepared a simple app/boilerplate you can use for your applications:
- Download/clone the application repository. It is a simplified version of CRA boilerplate with one single REST call which retrieves ten incidents from ServiceNow. Install all dependencies by
npm install
- Specify you ServiceNow instance URL as a proxy server in
package.json
file (line #5). - Provide ServiceNow username & password in
.env
file. Those will be used by the application when making REST calls. Make sure the user has access toincident
table in ServiceNow.
That’s it. Run the app by npm start
and you should see 10 incidents from you ServiceNow instance:
It is a very simple application and it uses axios package to make REST calls.
Production environment
Well, you will be surprised, but you don’t need to do anything here.
Unlike the development environment, we don’t use username & password in production. We use а session token provided by ServiceNow. And it’s already wired into the boilerplate.
In the index.html
file we retrieve a session token in a Jelly script (lines ##11–15) and store it as a property of window object (line #23):
And then we use that token as a default authentication method when initializing the app (line #16):
To deploy the application into ServiceNow you need to perform the following steps (check this article for step-by-step tutorial how to deploy into ServiceNow):
- Build the application by executing
npm run build
. - Save JS and CSS files from Build folder as Style Sheets in ServiceNow.
- Save HTML file from Build folder as a UI page. Update references to JS/CSS files with .cssdbx links.
And this is it:
You can even run React application inside of ServiceNow UI16: