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.
<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><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#
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
-1when no HTTP request succeeded. - A JSON success object when the call succeeds.
- A JSON error object with a message when the status is
4xxor5xx. - 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#
- FusionAuth/Fideo Identity Verification - Shows how to perform identity verification using a third party API during self-service registration
- API Consents Platform - Example repo for a third-party application platform with scopes and consent management.
- Authenticate with SAML example - Example of authenticating with SAML
- AWS CloudFront redirect to URL - This example documents how to use a AWS CloudFront Function to redirect to country-specific URLs, such as a FusionAuth instance.
- Backend for Frontend Authentication - Example apps for BFF pattern showing homegrown BFF and BFF using FusionAuth's hosted backend
- Consents - Example using advanced registration forms and consents
- Deeplinking - Example returning users to the same page they logged in on
- Device grant - An example of the Device Authorization grant
- Family API - Demonstrates how to use the family API to grant access to restricted sections of a web app
- Family management - Family management and consent creation
- Fine-grained authorization example - Example of using fine-grained authorization with FusionAuth
- FusionAuth + Fastify: Using Links with Google & X.com - Example Fastify application showing how to use FusionAuth links to connect user accounts with external providers like Google and X.com
- FusionAuth Centralized Sessions - Example of centralized sessions between two different custom applications
- FusionAuth SSO - Two Express applications that share a FusionAuth SSO session and log out together with front-channel logout
- Gaming and device grant - Example using the Device Authorization grant to provide authentication to a game.
- Gatsby OAuth - An example of using Gatsby with the Authorization Code grant and PKCE
- Github Actions - This sample application demonstrates how to use a GitHub Action to run Playwright tests against a simple Node.js Express.js application that logs in with FusionAuth.
- JavaScript Express API quickstart - JavaScript Express quickstart tutorial showing how to integrate FusionAuth with a JavaScript Express API
- Javascript JWT - JWT creation and decoding examples with javascript
- JavaScript NextJS quickstart - JavaScript NextJS quickstart tutorial showing how to integrate FusionAuth with a JavaScript NextJS application
- JavaScript Remix quickstart - JavaScript Remix quickstart tutorial showing how to integrate FusionAuth with a JavaScript Remix application
- JWT Auth and a Microservices gateway - API gateway and microservices secured using JWT auth
- Machine to machine - Example repo for machine to machine interaction.
- Magic links login - Next.js app which uses magic links for authentication
- Microservices gateway - API gateway and microservices
- Migrating from Passport example - Example of migrating from Node-based authentication
- Modeling Organizations - Node.js Express sample application for the Modeling Organizations guide.
- Modern guide to OAuth - Code examples from the Modern Guide To OAuth
- Multi-Application Dashboard - Two Express applications and a custom theme Index page that links to both, with SSO between them
- Multi-tenant application - Two nodejs applications in different tenants, living in different domains.
- React Native quickstart - React Native quickstart tutorial showing how to integrate FusionAuth with a React Native mobile application
- Restrict Simultaneous Logins (Simple) - Demonstrates how to limit the number of devices a user can simultaneously log in from, asking them to sign out from an existing session in order to continue
- Restrict Simultaneous Logins (User-friendly) - Demonstrates how to limit the number of devices a user can simultaneously log in from, allowing them to sign out via interface from other sessions
- Start Here Tutorial App - An express/JavaScript application used for a walkthrough of a FusionAuth setup
- Twitter login - Node/express app which uses Twitter for authentication
- User actions example - Corresponds to the user actions guide tutorial
- WebAuthn - Helper code for WebAuthn ceremonies
- Webhooks - Example webhook listeners that verify signatures and read context passed from API requests
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.
Related
Learn how to bind tokens to the browser with DPoP using the FusionAuth React, Angular, or Vue SDK.
Learn how to add login, logout, and registration to your Angular application with the FusionAuth Angular SDK.
Learn about every configuration option the FusionAuth React, Angular, and Vue SDKs accept.