# Create and rotate an API key with ArcGIS REST JS

> Automate API key creation and rotation in Node.js with createApiKey, updateApiKey and invalidateApiKey, which wrap the four REST requests.

Interactive version: http://www.rauljimenez.info/arcgis-tutorials/api-key-rest-js/

## What you will build

Two Node.js scripts with [ArcGIS REST JS](https://developers.arcgis.com/arcgis-rest-js/):

* `create-api-key.mjs` creates the API key credentials and generates the first key, in slot 1.
* `rotate-api-key.mjs` rotates that key without downtime, using the second slot.

Each REST JS function wraps several REST requests; the [REST API tutorial](../api-key-rest/) shows them one by one.

<details>
<summary>Check prerequisites</summary>
<p>An ArcGIS Location Platform, ArcGIS Online, or ArcGIS Enterprise account with a Creator user type or higher and the <strong>Generate API keys</strong> and <strong>Assign privileges to OAuth 2.0 applications</strong> privileges. Ideally a service user with only those.</p>
<p>Node.js 20.12 or later, for <code>process.loadEnvFile</code>.</p>
</details>

## Install the packages

Run `npm install` in the project folder. `@esri/arcgis-rest-request` signs you in; `@esri/arcgis-rest-developer-credentials` creates and manages credentials.

```json title="code/package.json" region="/dependencies"
"dependencies": {
  "@esri/arcgis-rest-developer-credentials": "^4.11.0",
  "@esri/arcgis-rest-request": "^4.11.0"
}
```

## Configure the scripts

Copy `.env.example` to `.env` and fill it in. `.gitignore` keeps it out of your repository.

Every request goes to the portal's sharing API (`https://www.arcgis.com/sharing/rest` for ArcGIS Online and ArcGIS Location Platform, `https://<host>/<web-adaptor>/sharing/rest` for ArcGIS Enterprise.):

- **Portal URL** (`portalUrl`)

The scripts sign in with app credentials (Backend jobs can't sign in as you: a username and password don't work with SAML/SSO or MFA. Create the app credentials in the portal as a service user and assign them that user's privileges. They are not the client ID and secret of the API key item the script creates.), not as you:

- **App credentials client ID** (`appClientId`)
- **App credentials client secret** (`appClientSecret`)

> **Keep the `client_secret` in a secret manager**, and create the app credentials as a service user with only the privileges these scripts need. With admin privileges, the secret can do almost as much damage as your password.

<details>
<summary>Why the app credentials need their owner's privileges</summary>
<p>Creating and rotating keys with app credentials needs their owner's user privileges: on ArcGIS Location Platform, <code>createItem</code>, <code>generateApiTokens</code> and <code>assignPrivilegesToApps</code> alone were not enough. The secret can't sign in or change your password, but it can do whatever those privileges allow.</p>
<p>In production, the same variables can come from the environment or a secret manager instead of <code>.env</code>.</p>
</details>

```text title="code/.env.example" region="config"
# Configure the scripts: copy this file to .env and fill it in
PORTAL="https://www.arcgis.com/sharing/rest"

# App credentials of a service user, with that user's privileges (not the API key item's)
APP_CLIENT_ID="YOUR_APP_CLIENT_ID"
APP_CLIENT_SECRET="YOUR_APP_CLIENT_SECRET"
```

## Import the functions

* `ApplicationCredentialsManager`: signs in with app credentials.
* `createApiKey`: creates the credentials.
* `writeFile`: saves the item ID and slot to `state.json`.

```javascript title="code/create-api-key.mjs" region="imports"
// Import the functions
import { writeFile } from "node:fs/promises";
import { ApplicationCredentialsManager } from "@esri/arcgis-rest-request";
import { createApiKey } from "@esri/arcgis-rest-developer-credentials";
```

## Sign in

`process.loadEnvFile()` loads `.env`. `ApplicationCredentialsManager` gets an app token with the client ID and secret, and renews it when it expires.

<details>
<summary>Other ways to sign in</summary>
<p>To sign in as a user, use <code>ArcGISIdentityManager.beginOAuth2</code> (OAuth 2.0) or <code>ArcGISIdentityManager.signIn</code> (username and password).</p>
<table>
<tr><th>Method</th><th>Use it for</th><th>Limits</th></tr>
<tr><td>Username and password</td><td>Trying things on your machine</td><td>Doesn't work with SAML/SSO or MFA accounts; the password ends up in code or the environment.</td></tr>
<tr><td><a href="https://developers.arcgis.com/documentation/security-and-authentication/user-authentication/">User authentication</a> (OAuth 2.0)</td><td>Interactive scripts and apps</td><td>The refresh token expires, and changing the password invalidates it.</td></tr>
<tr><td><a href="https://developers.arcgis.com/documentation/security-and-authentication/app-authentication/">App credentials</a></td><td>Backend jobs, such as scheduled rotation</td><td>They need their owner's user privileges, and the <code>client_secret</code> can do whatever those privileges allow. Both scripts use them.</td></tr>
</table>
</details>

```javascript title="code/create-api-key.mjs" region="sign-in"
// Sign in
process.loadEnvFile(); // reads .env
const authentication = ApplicationCredentialsManager.fromCredentials({
  clientId: process.env.APP_CLIENT_ID,
  clientSecret: process.env.APP_CLIENT_SECRET,
  portal: process.env.PORTAL,
});
```

## Create the credentials

`createApiKey` takes the same answers as the [portal's wizard](../api-key-portal/#add-item). Each comment in the code names the wizard screen the option comes from.

- **Privileges (comma-separated)** (`privileges`)

<small>See the [privileges reference](https://developers.arcgis.com/documentation/security-and-authentication/reference/privileges/).</small>

`httpReferrers`, the sites allowed to use the key, is empty so you can test from scripts or Postman.

> **Set your app's URL as a referrer before you ship a public app.** Without one, anyone who copies the key can use it from any site, billed to you. You can't change referrers or the expiration (30 days here) later without invalidating the key.

<details>
<summary>The four requests behind <code>createApiKey</code></summary>
<ol>
<li><code>content/users/&#123;user&#125;/addItem</code> creates the empty item: <code>type=Application</code>, <code>title</code>, <code>tags</code> and the description.</li>
<li><code>oauth2/registerApp</code> registers it with your <code>privileges</code> and <code>httpReferrers</code>, plus <code>appType=multiple</code> and <code>redirect_uris</code>, which come from OAuth 2.0 credentials: the endpoint requires them, but they don't affect the key. It returns the <code>client_id</code> and <code>client_secret</code>.</li>
<li><code>content/users/&#123;user&#125;/items/&#123;id&#125;/update</code> stores <code>apiToken1ExpirationDate</code> in epoch milliseconds. Slot 2 gets <code>-1</code>: no key yet.</li>
<li><code>oauth2/token</code> generates the key: <code>grant_type=client_credentials</code>, <code>apiToken=1</code> and <code>regenerateApiToken=true</code>, because <code>generateToken1</code> is <code>true</code>. On a slot that already holds a key, <code>true</code> replaces it and invalidates the old one at once.</li>
</ol>
<p>Wizard screens: <a href="../api-key-portal/#details">Item details</a>, <a href="../api-key-portal/#item-access">Item access</a>, <a href="../api-key-portal/#register">Privileges</a>, <a href="../api-key-portal/#expiration">Settings</a>, <a href="../api-key-portal/#generate">Generate API key</a>.</p>
</details>

```javascript title="code/create-api-key.mjs" region="create"
// Create the credentials
const expiration = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 30 days

const apiKey = await createApiKey({
  // Portal wizard › Item details
  title: "My API key credentials tutorial",
  description: "Key for the store locator app",
  tags: ["api key", "basemaps", "geocoding"],
  // Portal wizard › Privileges: services the key can call (+ portal:app:access:item:<id> per item)
  privileges: "premium:user:basemaps,premium:user:geocode".split(",").map((p) => p.trim()),
  // Portal wizard › Settings: domains allowed to use the key (empty = any site: set your app's URL before you ship)
  httpReferrers: [],
  // Portal wizard › Settings: expiration (max. 1 year)
  apiToken1ExpirationDate: expiration,
  // Portal wizard › Generate API key: generate the key in slot 1 now
  generateToken1: true,
  authentication,
});
```

## Save the key

`accessToken1` is the key in slot 1. The portal shows it only once: deploy it to your app. `state.json` keeps the item ID and slot for the rotation script, but not the key.

<details>
<summary>Where is the <code>client_secret</code>?</summary>
<p><code>createApiKey</code> removes it from the response. The other functions fetch it from <code>registeredAppInfo</code> when they need it.</p>
</details>

```javascript title="code/create-api-key.mjs" region="generate"
// Save the key
console.log("Item ID:", apiKey.item.id);
console.log("API key (slot 1):", apiKey.accessToken1);

// state.json is written by the scripts, unlike .env. It doesn't hold the key: deploy that to your app
// state.json: {"itemId": "a1f3c9e27b8d4e6f9c0b2d4e6f8a1c3e", "slot": 1}
await writeFile("state.json", JSON.stringify({ itemId: apiKey.item.id, slot: 1 }, null, 2));
```

## Rotate: import the functions

* `updateApiKey`: generates the key in the new slot.
* `invalidateApiKey`: invalidates the old key.
* `readFile`, `writeFile` and `createInterface`: read and update `state.json`, and wait while you deploy.

```javascript title="code/rotate-api-key.mjs" region="rotate-imports"
// Rotate: import the functions
import { readFile, writeFile } from "node:fs/promises";
import { createInterface } from "node:readline/promises";
import { ApplicationCredentialsManager } from "@esri/arcgis-rest-request";
import { invalidateApiKey, updateApiKey } from "@esri/arcgis-rest-developer-credentials";
```

## Rotate: start from the key in production

Rotation keeps a valid key at all times: generate a key in the free slot, deploy it, then invalidate the old one.

The script signs in with the same `.env` and reads the item and current slot from `state.json`.

```javascript title="code/rotate-api-key.mjs" region="rotate-config"
// Rotate: start from the key in production
process.loadEnvFile(); // reads .env
const authentication = ApplicationCredentialsManager.fromCredentials({
  clientId: process.env.APP_CLIENT_ID,
  clientSecret: process.env.APP_CLIENT_SECRET,
  portal: process.env.PORTAL,
});

// Item and slot of the key in production, saved by create-api-key.mjs
// state.json: {"itemId": "a1f3c9e27b8d4e6f9c0b2d4e6f8a1c3e", "slot": 1}
const { itemId, slot: currentSlot } = JSON.parse(await readFile("state.json", "utf8"));
```

## Find the free slot

The new key goes into the slot that isn't in production. Without `state.json`, `slotForKey` reads the slot from the key (A key ends in `AT1_` or `AT2_` plus eight characters.).

```javascript title="code/rotate-api-key.mjs" region="find-slot"
// Find the free slot
const newSlot = currentSlot === 1 ? 2 : 1;
```

## Generate the key in the new slot

`updateApiKey` sets the new slot's expiration and generates its key. The key in production keeps working.

> **Don't pass `privileges` or `httpReferrers` to `updateApiKey` here.** Changing them invalidates the keys of both slots.

<details>
<summary>REST requests</summary>
<p>An item <code>update</code> with the expiration, then <code>oauth2/token</code> with <code>apiToken</code> set to the new slot. Privileges and referrers would go through <code>{"oauth2/apps/{client_id}/update"}</code>.</p>
</details>

```javascript title="code/rotate-api-key.mjs" region="rotate-generate"
// Generate the key in the new slot
const expiration = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 30 days

const result = await updateApiKey({
  itemId,
  authentication,
  generateToken1: newSlot === 1,
  generateToken2: newSlot === 2,
  apiToken1ExpirationDate: newSlot === 1 ? expiration : undefined,
  apiToken2ExpirationDate: newSlot === 2 ? expiration : undefined,
});

const newKey = newSlot === 1 ? result.accessToken1 : result.accessToken2;
console.log(`New API key (slot ${newSlot}):`, newKey);
// New API key (slot 2): AAPTk3Lm9QzR2vWs8EoYbN4tHc7uJ1xA6dFg_example_pQ5nZwB.AT2_K9pLw4Zd
```

## Deploy the new key

Put the new key in production. The old key stays valid until you continue.

```javascript title="code/rotate-api-key.mjs" region="deploy"
// Deploy the new key
const prompt = createInterface({ input: process.stdin, output: process.stdout });
await prompt.question("Deploy the new key, then press Enter to invalidate the old one…");
prompt.close();
```

## Invalidate the old key

`invalidateApiKey` with the **old** slot (or old key) invalidates it; passing the new key would invalidate the one you just deployed. The script then saves the new slot to `state.json`.

<details>
<summary>REST request</summary>
<p><code>oauth2/revokeToken</code> with the item's <code>client_id</code>, <code>client_secret</code> and <code>apiToken</code> set to the old slot.</p>
</details>

```javascript title="code/rotate-api-key.mjs" region="invalidate"
// Invalidate the old key
const { success } = await invalidateApiKey({ itemId, authentication, apiKey: currentSlot });
console.log(`Old key in slot ${currentSlot} invalidated:`, success);

// The key in production is now in the new slot
await writeFile("state.json", JSON.stringify({ itemId, slot: newSlot }, null, 2));
```

API keys suit public apps. A backend script can authenticate as an application instead: [authenticate a Node.js script with ArcGIS REST JS](../oauth-app-rest-js/).

## Final code

### code/create-api-key.mjs

```javascript title="code/create-api-key.mjs"
// Create API key credentials and generate the first API key (slot 1).
// Run: node create-api-key.mjs
// Import the functions
import { writeFile } from "node:fs/promises";
import { ApplicationCredentialsManager } from "@esri/arcgis-rest-request";
import { createApiKey } from "@esri/arcgis-rest-developer-credentials";

// Sign in
process.loadEnvFile(); // reads .env
const authentication = ApplicationCredentialsManager.fromCredentials({
  clientId: process.env.APP_CLIENT_ID,
  clientSecret: process.env.APP_CLIENT_SECRET,
  portal: process.env.PORTAL,
});

// Create the credentials
const expiration = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 30 days

const apiKey = await createApiKey({
  // Portal wizard › Item details
  title: "My API key credentials tutorial",
  description: "Key for the store locator app",
  tags: ["api key", "basemaps", "geocoding"],
  // Portal wizard › Privileges: services the key can call (+ portal:app:access:item:<id> per item)
  privileges: "premium:user:basemaps,premium:user:geocode".split(",").map((p) => p.trim()),
  // Portal wizard › Settings: domains allowed to use the key (empty = any site: set your app's URL before you ship)
  httpReferrers: [],
  // Portal wizard › Settings: expiration (max. 1 year)
  apiToken1ExpirationDate: expiration,
  // Portal wizard › Generate API key: generate the key in slot 1 now
  generateToken1: true,
  authentication,
});

// Save the key
console.log("Item ID:", apiKey.item.id);
console.log("API key (slot 1):", apiKey.accessToken1);

// state.json is written by the scripts, unlike .env. It doesn't hold the key: deploy that to your app
// state.json: {"itemId": "a1f3c9e27b8d4e6f9c0b2d4e6f8a1c3e", "slot": 1}
await writeFile("state.json", JSON.stringify({ itemId: apiKey.item.id, slot: 1 }, null, 2));
```

### code/package.json

```json title="code/package.json"
{
  "name": "api-key-rest-js",
  "private": true,
  "type": "module",
  "scripts": {
    "create": "node create-api-key.mjs",
    "rotate": "node rotate-api-key.mjs"
  },
  "dependencies": {
    "@esri/arcgis-rest-developer-credentials": "^4.11.0",
    "@esri/arcgis-rest-request": "^4.11.0"
  }
}
```

### code/rotate-api-key.mjs

```javascript title="code/rotate-api-key.mjs"
// Rotate an API key: generate a key in the free slot, deploy it, then invalidate the old one.
// Run: node rotate-api-key.mjs
// Rotate: import the functions
import { readFile, writeFile } from "node:fs/promises";
import { createInterface } from "node:readline/promises";
import { ApplicationCredentialsManager } from "@esri/arcgis-rest-request";
import { invalidateApiKey, updateApiKey } from "@esri/arcgis-rest-developer-credentials";

// Rotate: start from the key in production
process.loadEnvFile(); // reads .env
const authentication = ApplicationCredentialsManager.fromCredentials({
  clientId: process.env.APP_CLIENT_ID,
  clientSecret: process.env.APP_CLIENT_SECRET,
  portal: process.env.PORTAL,
});

// Item and slot of the key in production, saved by create-api-key.mjs
// state.json: {"itemId": "a1f3c9e27b8d4e6f9c0b2d4e6f8a1c3e", "slot": 1}
const { itemId, slot: currentSlot } = JSON.parse(await readFile("state.json", "utf8"));

// Find the free slot
const newSlot = currentSlot === 1 ? 2 : 1;

// Generate the key in the new slot
const expiration = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 30 days

const result = await updateApiKey({
  itemId,
  authentication,
  generateToken1: newSlot === 1,
  generateToken2: newSlot === 2,
  apiToken1ExpirationDate: newSlot === 1 ? expiration : undefined,
  apiToken2ExpirationDate: newSlot === 2 ? expiration : undefined,
});

const newKey = newSlot === 1 ? result.accessToken1 : result.accessToken2;
console.log(`New API key (slot ${newSlot}):`, newKey);
// New API key (slot 2): AAPTk3Lm9QzR2vWs8EoYbN4tHc7uJ1xA6dFg_example_pQ5nZwB.AT2_K9pLw4Zd

// Deploy the new key
const prompt = createInterface({ input: process.stdin, output: process.stdout });
await prompt.question("Deploy the new key, then press Enter to invalidate the old one…");
prompt.close();

// Invalidate the old key
const { success } = await invalidateApiKey({ itemId, authentication, apiKey: currentSlot });
console.log(`Old key in slot ${currentSlot} invalidated:`, success);

// The key in production is now in the new slot
await writeFile("state.json", JSON.stringify({ itemId, slot: newSlot }, null, 2));
```

### code/.env.example

```text title="code/.env.example"
# Configure the scripts: copy this file to .env and fill it in
PORTAL="https://www.arcgis.com/sharing/rest"

# App credentials of a service user, with that user's privileges (not the API key item's)
APP_CLIENT_ID="YOUR_APP_CLIENT_ID"
APP_CLIENT_SECRET="YOUR_APP_CLIENT_SECRET"
```

### code/.gitignore

```text title="code/.gitignore"
# Secrets (.env) and state written by the scripts
.env
state.json
node_modules/
```
