Docs Menu
Docs Home
/ /
Atlas Device SDKs
/ /

Create & Manage User API Keys - React Native SDK

On this page

  • React Hooks
  • Create a User API Key
  • Look up a User API Key
  • Enable or Disable an API Key
  • Delete an API Key

User API keys allow devices or services to communicate with App Services on behalf of a user without sharing that users credentials. User API keys can be revoked at any time by the authenticated user. User API keys do not expire on their own.

You can manage a user API key with the ApiKeyAuth client accessed with an authenticated user's User.apiKeys property.

If you are using @realm/react, you can access a user's ApiKeyAuth client with the useUser() hook in a component wrapped by UserProvider.

import {useUser} from '@realm/react';
const user = useUser();
const createUserApiKey = async () => {
const {_id, key, name, disabled} = await user?.apiKeys.create(apiKeyName);
// ...Do something with API key like save it
// or share it with external service that authenticates
// on user's behalf.
};

To create a new user API key, pass a name that's unique among all of the user's API keys to ApiKeyAuth.create().

The SDK returns the value of the user API key when you create it. Make sure to store the key value securely so that you can use it to log in. If you lose or do not store the key value there is no way to recover it. You will need to create a new user API key.

You cannot create a user API key for a server API key or an anonymous user.

const {_id, key, name, disabled} = await user?.apiKeys.create(apiKeyName);

To get an array that lists all of a user's API keys, call ApiKeyAuth.fetchAll().

To find a specific API key, pass the key's _id to ApiKeyAuth.fetch().

const getUserApiKey = async () => {
// List all of a user's keys
const keys = await user.apiKeys.fetchAll();
// Get a specific key by its ID
const key = await user!.apiKeys.fetch(apiKey!._id);
};

To enable or disable a user API key, pass the key's _id to ApiKeyAuth.enable() or ApiKeyAuth.disable(). When a key is disabled, it cannot be used to log in on behalf of the user.

await user!.apiKeys.enable(cloudApiKey!._id);
await user!.apiKeys.disable(cloudApiKey!._id);

To permanently delete a user API, pass the key's _id to ApiKeyAuth.delete(). Deleted keys cannot be recovered.

await user!.apiKeys.delete(cloudApiKey!._id);

Back

Link User Identities