---
id: gatey-javascript-api
title: JavaScript API
slug: /gatey/javascript-api
sidebar_position: 30
description: Client-side helpers exposed under globalThis.WpSuite.plugins.gatey — Cognito/session helpers plus shared WP Suite readiness utilities.
tags: [gatey, javascript, api, events, aws, amplify, cognito]
hide_title: true
---

## JavaScript API

Gatey exposes its public runtime surface under the **WP Suite global**:

- `globalThis.WpSuite.plugins.gatey` (plugin object)
- `globalThis.WpSuite.plugins.gatey.cognito` (Cognito/session helpers)

All helper methods are async and return a `Promise` unless noted otherwise.

---

## Runtime helpers (shared WP Suite contract)

WP Suite plugins share a small common runtime contract (from `@smart-cloud/wpsuite-core`).

### Helper accessors

If you are bundling `@smart-cloud/wpsuite-core`, you can also use:

- `getWpSuite()` → returns the global `WpSuite` object (or `undefined`)
- `getPlugin("gatey" | "...")` → returns a plugin object from the registry

(These are thin wrappers around `globalThis.WpSuite`.)


### Plugin status

`WpSuite.plugins.gatey.status` can be one of:

- `unavailable` — plugin not present / not initialized yet
- `initializing` — booting up
- `available` — ready to use
- `error` — failed to initialize

### Wait until Gatey is ready

There are three common ways to wait:

**1) `onReady(cb)`**

```js
globalThis.WpSuite?.plugins?.gatey?.onReady?.(() => {
  console.log("Gatey is ready");
});
```

**2) `availability()` (await-ready with timeout)**

Resolves to `available`, `unavailable`, or `error` (it never returns `initializing`).

```js
const res = await globalThis.WpSuite?.plugins?.gatey?.availability?.();
if (res !== "available") {
  console.warn("Gatey not available:", res);
}
```

**3) Gatey core wrappers (`waitForGateyReady`)**

If your build includes the Gatey core package, you can use its convenience wrappers:

- `getGateyPlugin()`
- `waitForGateyReady(timeoutMs = 8000)`

These are thin helpers on top of the events below.

### Readiness / error events

Gatey emits DOM events you can listen to:

- `wpsuite:gatey:ready`
- `wpsuite:gatey:error`

```js
window.addEventListener("wpsuite:gatey:ready", () => console.log("ready"));
window.addEventListener("wpsuite:gatey:error", () => console.log("error"));
```

---

## Cognito helper methods

The helpers below live under `WpSuite.plugins.gatey.cognito`.

> Notes
> - Unless explicitly marked as **sync**, helpers return a `Promise`.
> - Types below are intentionally simplified for documentation.

| Method | Returns | Use case |
|---|---|---|
| `getUsername()` | `Promise<string>` | Display the current username. |
| `getUserAttributes()` | `Promise<Record<string, string>>` | Prefill a form with profile data. |
| `getMfaPreferences()` | `Promise<object>` | Show MFA status. |
| `clearMfaPreferences()` | `Promise<void>` | One-click TOTP disable. |
| `isAuthenticated()` | `Promise<boolean>` | Guard a route or action. |
| `isInGroup("admin")` | `Promise<boolean>` | Role-based UI. |
| `getGroups()` | `Promise<string[]>` | Render a badge list. |
| `getRoles()` | `Promise<string[]>` | IAM role switcher / role-aware UI. |
| `getScopes()` | `Promise<string[]>` | Scope-aware buttons. |
| `getPreferredRole()` | `Promise<string | null>` | Auto-select a role. |
| `setLanguage("en")` | `Promise<void>` | Switch the Authenticator’s UI language at runtime. |
| `setDirection("auto" \| "ltr" \| "rtl")` | `Promise<void>` | Override layout direction (or let Gatey auto-detect). |
| `signOut()` | `Promise<void>` | Custom logout button (ends the Cognito session and runs Gatey hooks). |
| `getAmplifyConfig()` | `Promise<object>` | Debug the currently active Amplify configuration. |
| `store` | `Promise<object>` | Access the internal Redux store (advanced use). |
| `observeStore(store, selector, onChange)` | `() => void` (**sync**) | Subscribe to `store` changes with a selector (returns `unsubscribe`). |
| `get(request)` | `Promise<any>` | Signed API call via `aws-amplify/api`. |
| `post(request)` | `Promise<any>` | Signed API call via `aws-amplify/api`. |
| `put(request)` | `Promise<any>` | Signed API call via `aws-amplify/api`. |
| `del(request)` | `Promise<any>` | Signed API call via `aws-amplify/api`. |

### Example: show user and roles

```js
const gatey = globalThis.WpSuite?.plugins?.gatey;
const cognito = gatey?.cognito;

const ok = (await gatey?.availability?.()) === "available";
if (!ok) return;

console.log("User:", await cognito.getUsername());
console.log("Roles:", await cognito.getRoles());
```

### Example: observe auth state changes (observeStore)

`cognito.store` resolves to the internal Redux store. You can use `observeStore` to run a callback when a selected slice changes.

```js
const cognito = globalThis.WpSuite?.plugins?.gatey?.cognito;

cognito?.store?.then((store) =>
  cognito.observeStore(
    store,
    (state) => state.signedIn,
    (signedIn, prev) => {
      // Reload the page if the visitor signs out
      if (prev !== undefined && !signedIn) {
        window.location.reload();
      }
    }
  )
);
```

Common selectors include:

- `state.signedIn` — `true | false`
- `state.account` — `{ username, userAttributes, mfaPreferences, ... }`
- `state.amplifyConfig` — the Amplify resources/config Gatey initialized with

### Example: signed API request (get/post/put/del)

```js
const cognito = globalThis.WpSuite?.plugins?.gatey?.cognito;
const gatey = globalThis.WpSuite?.plugins?.gatey;

const ok = (await gatey?.availability?.()) === "available";
if (!ok) return;

const orders = await cognito.post({
  apiName: "backend",
  path: "/orders",
  options: { body: { status: "OPEN" } },
});

console.table(orders);
```

---

## Notes

- Always guard calls with optional chaining (`?.`) in case Gatey is not installed on the page.
- If you are writing a plugin/theme that depends on Gatey, prefer `availability()` / `onReady()` / `waitForGateyReady()` over polling.
