TypeScript Client Library

On this page

The FusionAuth TypeScript client library integrates FusionAuth with applications written for browsers or Node.js. The library supports applications written in TypeScript and JavaScript. The source code is in the TypeScript client GitHub repository.

Install#

NPM Package#

Run the following command:

$ npm install @fusionauth/typescript-client

Browser Bundle#

To use FusionAuthClient in a browser application, fetch the npm module from esm.sh or cdn.jsDelivr in a script tag.

esm.sh
<script type="module">    import { FusionAuthClient } from 'https://esm.sh/@fusionauth/typescript-client';    // first parameter is the API key, see the note below    const client = new FusionAuthClient(null, 'https://your-fusionauth-url.com');    client.exchangeOAuthCodeForAccessTokenUsingPKCE(...)      .then(response => console.log('Success:', response))      .catch(error => console.error('Error:', error));  </script>
cdn.jsDelivr
<script type="module">  import { FusionAuthClient } from 'https://cdn.jsdelivr.net/npm/@fusionauth/typescript-client/+esm';    const client = new FusionAuthClient(null, 'https://your-fusionauth-url.com');</script>

Examples#

Note

Frontend code such as a web browser has no secure place to store an API key. To make API requests that don't require an API key, pass null for the API key parameter.

The following examples assume FusionAuth runs at http://localhost:9011. Each example contains an API key. Replace the API key with your own. When FusionAuth doesn't run locally, replace the host URL too.

Each example uses retrieveUserByEmail as a basic use case. The examples use TypeScript, and you can write the same code in plain JavaScript.

Node.js#

import {FusionAuthClient} from '@fusionauth/typescript-client';
const client = new FusionAuthClient('bf69486b-4733-4470-a592-f1bfce7af580', 'https://local.fusionauth.io');
client.retrieveUserByEmail('user@example.com')
      .then(clientResponse => {
        console.log("User:", JSON.stringify(clientResponse.response.user, null, 2));
      }).catch(console.error);

For the full example, see the Node.js example source code.

Browser#

In the browser, the library exports all objects under the FusionAuth namespace. The namespace keeps the objects out of the global namespace.

<script src="fusionauth-typescript-client.min.js"></script>
<script>
const client = new FusionAuth.FusionAuthClient('bf69486b-4733-4470-a592-f1bfce7af580', 'https://local.fusionauth.io');
client.retrieveUserByEmail('user@example.com')
      .then(clientResponse => {
        console.log("User:", JSON.stringify(clientResponse.response.user, null, 2));
      }).catch(console.error);
</script>

For the full example, see the browser example source code.

Hybrid#

A hybrid project runs the same code as the Node.js example in the browser and in Node.js. Browser bundles expose any API key to users, so avoid API keys in hybrid code.

The build script is the difference. Instead of compiling with tsc and running Node.js on the resulting JavaScript, use a tool such as browserify or webpack to build the script. This example uses browserify.

Choose the command for your target. To compile for Node.js, run:

$ tsc

To compile for the browser, run:

$ npm run build-browser

Alternatively, build for the browser with the longer command:

$ npx browserify example.ts --debug -p tsify -t browserify-shim -o dist/example-browser.js

For the full example, see the hybrid example source code.

Usage Suggestions#

Choose a Use Case#

Client libraries wrap the REST API. You can use a client library for two tasks.

The main task is calling the FusionAuth APIs from code. You get auto-completion and typed objects, which helps when you script configuration, automate common tasks, or copy existing Applications and Groups. The API documentation lists the JSON structure of every request and which fields each call requires. When you need the details, read the API documentation and the library source code.

The secondary task is exchanging an authorization code for tokens in the Authorization Code grant. For this task, use an OAuth library for your language instead. For a list of libraries, see the community curated list.

Client libraries don't provide higher level functionality such as token management. To request that functionality, comment on or upvote the open issue.

When a client library doesn't fit your needs, call the REST API directly.

Requests and Responses#

Each library maps a request object to the JSON that the matching API method requires. Depending on the API call, the request object is a set of string parameters or a complex object. When you use a language without static typing, read the API documentation for the operation to learn the expected fields.

Each library returns a response object with these fields:

  • A status that matches the HTTP status code from the API. The status is -1 when no HTTP request succeeded.
  • A JSON success object when the call succeeds.
  • A JSON error object with a message when the status is 4xx or 5xx.
  • An exception object when the library sent no request or the server returned no usable response.

Use Separate Clients for API Key Scopes#

When a script calls endpoints with different API key scopes, create one client instance per scope. For example, Entities accept a tenant-scoped API key, but Entity Types and Lambdas require a global API key.

Follow these rules when your library lets you set a Tenant Id on the client instance:

  • Set the Tenant Id on the tenant-scoped client only.
  • Don't change the Tenant Id on a shared client between calls.
  • Don't send a tenant header to a global-only endpoint. The endpoint fails with a 401.

Set the Tenant Id#

To set the Tenant Id on a client instance, call setTenantId(). Create a separate client instance for each API key scope, as described above.

Client Authentication#

You can use this client library in an application that can't securely store secrets, such as a native mobile application or a single page application running in the browser.

For these applications, turn off Require authentication in the FusionAuth Application configuration. Then use PKCE to secure communication with the Token endpoint. To exchange the authorization code, call the exchangeOAuthCodeForAccessTokenUsingPKCE client method.

Example Apps#

Update Policy#

FusionAuth releases new versions of the SDKs and client libraries to track the FusionAuth API. SDKs and client libraries may also receive bug fixes, security patches, tests, code samples, and documentation changes.

These releases may update dependencies, language engines, and operating systems, because FusionAuth follows the deprecation and sunsetting policies of the underlying technologies. When the maintainer deprecates a language, framework, or operating system, FusionAuth deprecates the SDKs and client libraries that depend on the technology. FusionAuth then updates the SDKs and client libraries to use a newer version.

For more information, see Update a Client Library.