# Javascript

The `@propelauth/javascript` library is designed for any frontend application. While you should prefer a more specific framework, like [React](https://docs.propelauth.com/reference/frontend-apis/react), whenever possible, this library has been used in applications with Svelte, Angular, Vue, and more.

---

## [Installation and Usage](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#installation-and-usage)

```bash
npm install @propelauth/javascript
```

and then you can import it:

```js
import { createClient } from "@propelauth/javascript";
```

Alternatively, you can use a CDN:

```html
<script
    src="https://www.unpkg.com/@propelauth/javascript@2.0.11/dist/javascript.min.js"
    integrity="sha384-FENNH2f7QuQvkZJBL7jebLr0OtYKgTA2iq+C5g3VXXX7SBwWmeMMoc+pBBtcn76G"
    crossorigin="anonymous"></script>
```

then a global PropelAuth object will be created, and you can call createClient from it:

```html
<script>
  PropelAuth.createClient({...});
</script>
```

---

## [Using the Javascript library](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#using-the-javascript-library)

You'll create a client using the [createClient](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#create-client) function, and then you can use the client to get information about the current user.

You can also enable background token refresh, which will automatically refresh the user's information periodically and on key events (e.g. user switches tabs, reconnects to the internet, etc).

---

## [createClient](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#create-client)

Creates an authentication client which manages your user's [access token](https://docs.propelauth.com/recipes/access-tokens), fetches user information, and provides other useful authentication functions.

The client also refreshes auth information when a user switches focus to your tab or reconnects (if they were offline).

```js
const authClient = createClient({
  // The base URL where your authentication pages are hosted.
  // You can find this under the Frontend Integration section for your project.
  authUrl: "https://auth.yourdomain.com",

// If true, periodically refresh the access token in the background.
  // This helps ensure you always have a valid token ready to go. Default true.
  enableBackgroundTokenRefresh: true,
});
```

---

## [getAuthenticationInfoOrNull](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-authentication-info-or-null)

If the user is logged in, this method returns an [AuthenticationInfo](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#authentication-info) object with information about the user. Otherwise, this method returns null.

The promise will generally resolve immediately, unless our current information is stale in which case it will make an API request.

### Arguments
- Name `forceRefresh` Type boolean Description

If true, the client will make an API request to get the latest information. Otherwise, it will use the cached information if it is still valid.

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

const authInfo = await authClient.getAuthenticationInfoOrNull()
if (authInfo) {
    console.log("User is logged in as", authInfo.user.email)
} else {
    console.log("User is not logged in")
}
```

---

## [AuthenticationInfo](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#authentication-info)

AuthenticationInfo is an object that contains information about the current user. It is returned from [getAuthenticationInfoOrNull](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-authentication-info-or-null).

- Name `accessToken` Type string Description

The user's [access token](https://docs.propelauth.com/recipes/access-tokens). You can use this to make API requests to your backend.

- Name `user` Type User Description

The user's information. See [User](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#user) for more information.

- Name `userClass` Type UserClass Description

Similar to [User](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#user), but instead of just being a JSON object, this is a class with helper functions (e.g. `getOrg`, `isImpersonating`). See [UserClass](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#user-class) for more information.

- Name `orgHelper` Type OrgHelper Description

A helper class for accessing the user's organization information. See [OrgHelper](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#org-helper) for more information.

- Name `accessHelper` Type AccessHelper Description

A helper class for accessing the user's roles and permissions. See [AccessHelper](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#access-helper) for more information.

- Name `impersonatorUserId` Type string | undefined Description

If the current user is being impersonated, this will be the ID of the impersonator. See [User Impersonation](https://docs.propelauth.com/overview/user-management/user-impersonation) for more information.

---

## [User](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#user)

This is the object that contains all the information about the current user. It is within the [AuthenticationInfo](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-authentication-info-or-null).

### Properties

- Name `userId` Type string Description

The user's unique ID

- Name `email` Type string Description

The user's email address

- Name `createdAt` Type number Description

The timestamp of when the user was created

- Name `firstName` Type string | undefined Description

The user's first name

- Name `lastName` Type string | undefined Description

The user's last name

- Name `username` Type string | undefined Description

The user's username

- Name `properties` Type object | undefined Description

Additional properties set on the user. See [User Properties](https://docs.propelauth.com/overview/user-management/user-properties) for more information.

- Name `pictureUrl` Type string | undefined Description

The URL of the user's profile picture

- Name `hasPassword` Type boolean Description

Whether the user has a password set. This will be false for users that signed up with a social provider (e.g. Google, Facebook), magic link, or SAML.

- Name `hasMfaEnabled` Type boolean Description

Whether the user has 2FA authentication enabled

- Name `canCreateOrgs` Type boolean Description

Whether the user can create organizations

- Name `legacyUserId` Type string | undefined Description

The user's legacy user ID. This is only set if you migrated from an external source. See [Migrating Users](https://docs.propelauth.com/migrations) for more information.

- Name `impersonatorUserId` Type boolean Description

---

## [UserClass](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#user-class)

Similar to [User](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#user), but instead of just being a JSON object, this is a class with helper functions (e.g. `getOrg`, `isImpersonating`). It is within the [AuthenticationInfo](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-authentication-info-or-null) returned from [getAuthenticationInfoOrNull](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-authentication-info-or-null).

### Properties

In addition to all the properties on [User](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#user), this contains:

- Name `getOrg` Type (orgId: string) => OrgMemberInfoClass | undefined Description

Returns the [OrgMemberInfoClass](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#org-member-info-class) for the given org ID

- Name `getOrgByName` Type (orgName: string) => OrgMemberInfoClass | undefined Description

Returns the [OrgMemberInfoClass](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#org-member-info-class) for the given org name

- Name `getUserProperty` Type (key: string) => unknown | undefined Description

Returns the value of a user property. See [User Properties](https://docs.propelauth.com/overview/user-management/user-properties) for more information.

- Name `getOrgs` Type () => OrgMemberInfoClass[] Description

Returns all orgs that the user is a member of

- Name `isImpersonating` Type () => boolean Description

Whether the current user is being impersonated by someone else. See [User Impersonation](https://docs.propelauth.com/overview/user-management/user-impersonation) for more information.

- Name `isRole` Type (orgId: string, role: string) => boolean Description

Whether the user has the given role in the given org

- Name `isAtLeastRole` Type (orgId: string, role: string) => boolean Description

Whether the user has at least the given role in the given org

- Name `hasPermission` Type (orgId: string, permission: string) => boolean Description

Whether the user has the given permission in the given org

- Name `hasAllPermissions` Type (orgId: string, permissions: string[]) => boolean Description

Whether the user has all the given permissions in the given org

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

const authInfo = await authClient.getAuthenticationInfoOrNull()
if (!authInfo) {
    console.log("User is not logged in")
    return;
}

console.log("User is logged in as", authInfo.userClass.email)
if (authInfo.userClass.isImpersonating()) {
    console.log("User is being impersonated by", authInfo.userClass.impersonatorUserId)
}
```

---

## [OrgMemberInfoClass](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#org-member-info-class)

Similar to `OrgMemberInfo`, but instead of just being a JSON object, this is a class with helper functions (e.g. `isRole`, `hasPermission`). It is returned from functions on the `UserClass` like [UserClass.getOrg](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#user-class) and [UserClass.getOrgByName](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#user-class).

### Properties

- Name `orgId` Type string Description

The ID of the organization

- Name `orgName` Type string Description

The name of the organization

- Name `urlSafeOrgName` Type string Description

The URL-safe name of the organization

- Name `userAssignedRole` Type string Description

The role of the user within this organization

- Name `userInheritedRolesPlusCurrentRole` Type string[] Description

The role of the user within this organization plus each inherited role

- Name `userPermissions` Type string[] Description

The permissions of the user within this organization

- Name `orgMetadata` Type object Description

A JSON blob of the org's metadata

- Name `isRole` Type (role: string) => boolean Description

Whether the user has the given role in this organization

- Name `isAtLeastRole` Type (role: string) => boolean Description

Whether the user has at least the given role in this organization

- Name `hasPermission` Type (permission: string) => boolean Description

Whether the user has the given permission in this organization

- Name `hasAllPermissions` Type (permissions: string[]) => boolean Description

Whether the user has all the given permissions in this organization

- Name `orgRoleStructure` Type string Description

The role structure set for your project. See [multi role per user](https://docs.propelauth.com/overview/authorization/managing-roles-permissions#multiple-roles-per-user) for more information.

- Name `userAssignedAdditionalRoles` Type string[] Description

If using multiple roles per user, returns an array of roles that the user belongs to. Excludes the `userAssignedRole`.

```js
const org = userClass.getOrg("my-org-id")
const isAdmin = org?.isRole("Admin")
if (isAdmin) {
    console.log("User is an admin in", org.orgName)
}
```

---

## [OrgHelper](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#org-helper)

`OrgHelper` is a helper class for accessing the user's organization information. It is within the [AuthenticationInfo](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-authentication-info-or-null) returned from [getAuthenticationInfoOrNull](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-authentication-info-or-null).

### Signature

```jsx
type OrgHelper = {
    // returns all orgs that the user is a member of
    getOrgs: () => OrgMemberInfo[],
    // returns all org ids that the user is a member of
    getOrgIds: () => string[],
    // returns org information for a given orgId
    getOrg: (orgId: string) => OrgMemberInfo | undefined,
    // returns org information for a given org by name
    getOrgByName: (orgName: string) => OrgMemberInfo | undefined,
}

type OrgMemberInfo = {
    orgId: string,
    orgName: string,
    urlSafeOrgName: string
    // The role of the user within this organization
    userAssignedRole: string
    userPermissions: string[]
}
```

### Example

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

const authInfo = await authClient.getAuthenticationInfoOrNull()
if (!authInfo) {
    console.log("User is not logged in")
    return;
}

const orgs = authInfo.orgHelper.getOrgs()
for (const org of orgs) {
    console.log("User is a", org.userAssignedRole, "in", org.orgName)
}
```

---

## [AccessHelper](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#access-helper)

A helper class for accessing the user's roles and permissions. It is within the [AuthenticationInfo](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-authentication-info-or-null) returned from [getAuthenticationInfoOrNull](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-authentication-info-or-null).

### Properties

- Name `isRole` Type (orgId: string, role: string) => boolean Description

Whether the user has the given role in the given org

- Name `isAtLeastRole` Type (orgId: string, role: string) => boolean Description

Whether the user has at least the given role in the given org

- Name `hasPermission` Type (orgId: string, permission: string) => boolean Description

Whether the user has the given permission in the given org

- Name `hasAllPermissions` Type (orgId: string, permissions: string[]) => boolean Description

Whether the user has all the given permissions in the given org

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

const authInfo = await authClient.getAuthenticationInfoOrNull()
if (!authInfo) {
    console.log("User is not logged in")
    return;
}

const isAdmin = authInfo.accessHelper.isAtLeastRole("my-org-id", "Admin")
console.log("User is an admin:", isAdmin)
```

---

## [logout](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#logout)

Logs the current user out.

### Arguments

- Name `redirectAfterLogout` * Type boolean Description

If true, the user will be redirected to the login page after logging out.

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

await authClient.logout(true)
```

---

## [getSignupPageUrl](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-signup-page-url)

Gets the URL of the signup page. This is useful if you want to link to the signup page from your application.

It takes in one optional argument which can control features like where the user returns to after logging in.

### Arguments
- Name `postSignupRedirectUrl` Type string Description

The URL to redirect the user to after they sign up. Set the default in your Dashboard.

- Name `userSignupQueryParameters` Type object Description

Query parameters to add to the signup URL.

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

const signupPageUrl = authClient.getSignupPageUrl({
    postSignupRedirectUrl: window.location.href,
    userSignupQueryParameters: {
        "ref": "my-cool-blog-post"
    }
})
```

---

## [getLoginPageUrl](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-login-page-url)

Gets the URL of the login page. This is useful if you want to link to the login page from your application.

It takes in one optional argument which can control features like where the user returns to after logging in.

### Arguments
- Name `postLoginRedirectUrl` Type string Description

The URL to redirect the user to after they log in. Set the default in your Dashboard.

- Name `userSignupQueryParameters` Type object Description

Query parameters to add to the login URL.

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

const loginPageUrl = authClient.getLoginPageUrl({
    postLoginRedirectUrl: window.location.href,
    userSignupQueryParameters: {
        "ref": "my-cool-blog-post"
    }
})
```

---

## [getAccountPageUrl](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-account-page-url)

Gets the URL of the account page. This is useful if you want to link to the account page from your application.

### Arguments
- Name `redirectBackToUrl` Type string Description

The URL to redirect the user to when they click the back button on the account page

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

const accountPageUrl = authClient.getAccountPageUrl({
    redirectBackToUrl: window.location.href
})
```

---

## [getOrgPageUrl](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-org-page-url)

Gets the URL of the organization page for a given org ID. If an org ID is not provided, one is chosen automatically.

### Arguments
- Name `orgId` Type string Description

The ID of the organization to get the URL for

- Name `redirectBackToUrl` Type string Description

The URL to redirect the user to when they click the back button on the account page

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

const orgPageUrl = authClient.getOrgPageUrl("my-org-id", {
    redirectBackToUrl: window.location.href
})
```

---

## [getCreateOrgPageUrl](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-create-org-page-url)

Gets the URL of the create organization page. This is useful if you want to link to the create organization page from your application.

### Arguments
- Name `redirectBackToUrl` Type string Description

The URL to redirect the user to when they click the back button on the account page

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

const createOrgPageUrl = authClient.getCreateOrgPageUrl({
    redirectBackToUrl: window.location.href
})
```

---

## [getSetupSAMLPageUrl](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-setup-saml-page-url)

Gets the URL of a page to setup [SAML](https://docs.propelauth.com/overview/authentication/saml) for the given org ID.

### Arguments
- Name `orgId` * Type string Description

The ID of the organization to get the URL for

- Name `redirectBackToUrl` Type string Description

The URL to redirect the user to when they click the back button on the account page

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

const setupSAMLPageUrl = authClient.getSetupSAMLPageUrl("my-org-id", {
    redirectBackToUrl: window.location.href
})
```

---

## [redirectToSignupPage](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#redirect-to-signup-page)

Redirects the user to the signup page. This is useful if you want to redirect the user to the signup page from your application.

It takes in one optional argument which can control features like where the user returns to after logging in.

### Arguments
- Name `postSignupRedirectUrl` Type string Description

The URL to redirect the user to after they sign up. Set the default in your Dashboard.

- Name `userSignupQueryParameters` Type object Description

Query parameters to add to the signup URL.

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

authClient.redirectToSignupPage({
    postSignupRedirectUrl: window.location.href,
    userSignupQueryParameters: {
        "ref": "my-cool-blog-post"
    }
})
```

---

## [redirectToLoginPage](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#redirect-to-login-page)

Redirects the user to the login page. This is useful if you want to redirect the user to the login page from your application.

It takes in one optional argument which can control features like where the user returns to after logging in.

### Arguments
- Name `postLoginRedirectUrl` Type string Description

The URL to redirect the user to after they log in. Set the default in your Dashboard.

- Name `userSignupQueryParameters` Type object Description

Query parameters to add to the login URL.

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

authClient.redirectToLoginPage({
    postLoginRedirectUrl: window.location.href,
    userSignupQueryParameters: {
        "ref": "my-cool-blog-post"
    }
})
```

---

## [redirectToAccountPage](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#redirect-to-account-page)

Redirects the user to the account page. This is useful if you want to redirect the user to the account page from your application.

### Arguments
- Name `redirectBackToUrl` Type string Description

The URL to redirect the user to when they click the back button on the account page

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

authClient.redirectToAccountPage({
    redirectBackToUrl: window.location.href
})
```

---

## [redirectToOrgPage](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#redirect-to-org-page)

Redirects the user to the organization page for a given org ID. If an org ID is not provided, one is chosen automatically.

### Arguments
- Name `orgId` Type string Description

The ID of the organization to get the URL for

- Name `redirectBackToUrl` Type string Description

The URL to redirect the user to when they click the back button on the account page

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

authClient.redirectToOrgPage("my-org-id", {
    redirectBackToUrl: window.location.href
})
```

---

## [redirectToCreateOrgPage](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#redirect-to-create-org-page)

Redirects the user to the create organization page. This is useful if you want to redirect the user to the create organization page from your application.

### Arguments
- Name `redirectBackToUrl` Type string Description

The URL to redirect the user to when they click the back button on the account page

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

authClient.redirectToCreateOrgPage({
    redirectBackToUrl: window.location.href
})
```

---

## [redirectToSetupSAMLPage](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#redirect-to-setup-saml-page)

Redirects the user to a page to setup [SAML](https://docs.propelauth.com/overview/authentication/saml) for the given org ID.

### Arguments
- Name `orgId` * Type string Description

The ID of the organization to get the URL for

- Name `redirectBackToUrl` Type string Description

The URL to redirect the user to when they click the back button on the account page

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

authClient.redirectToSetupSAMLPage("my-org-id", {
    redirectBackToUrl: window.location.href
})
```

---

## [getAccessTokenForOrg](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#get-access-token-for-org)

A function that will return an [access token](https://docs.propelauth.com/recipes/access-tokens) that only includes the metadata for the provided org, as well as the user's metadata. Recommended for use with [Active Org](https://docs.propelauth.com/recipes/active-org) or to shorten the length of the access token.

### Arguments
- Name `orgId` * Type string Description

The ID of the organization to get an access token for.

```js
import {createClient} from "@propelauth/javascript"
const authClient = createClient({...})

const orgAccessToken = await authClient.getAccessTokenForOrg("my-org-id")
```

---

## [Logged In Events](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#logged-in-events)

To be notified when the user logs in or out, you can add an event listener:

```ts
authClient.addLoggedInChangeObserver(observer: (isLoggedIn: boolean) => void)
authClient.removeLoggedInChangeObserver(observer: (isLoggedIn: boolean) => void)
```

---

## [Access Token Events](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#access-token-events)

To be notified when the access token changes, you can add an event listener:

```ts
addAccessTokenChangeObserver(observer: (accessToken: string | undefined) => void): void
removeAccessTokenChangeObserver(observer: (accessToken: string | undefined) => void): void
```

---

## [destroy](https://docs.propelauth.com/reference/frontend-apis/js?ref=propelauth.mymidnight.blog#destroy)

Cleanup the client and stop all background processes.

```ts
authClient.destroy()
```
