npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@teamhanko/hanko-frontend-sdk

v1.3.0

Published

A package for simplifying UI integration with the Hanko API. It is meant for use in browsers only.

Downloads

4,420

Readme

hanko-frontend-sdk

This package utilizes the Hanko API to provide functionality that allows an easier UI integration. It is meant for use in browsers only.

Installation

# npm
npm install @teamhanko/hanko-frontend-sdk

# yarn
yarn add @teamhanko/hanko-frontend-sdk

# pnpm
pnpm install @teamhanko/hanko-frontend-sdk

Usage

Import as a module:

import { Hanko } from "@teamhanko/hanko-frontend-sdk"

const hanko = new Hanko("http://localhost:3000")

With a script tag via CDN:

<script src="https://cdn.jsdelivr.net/npm/@teamhanko/hanko-frontend-sdk/dist/sdk.umd.js"></script>

<script>
    const hanko = new hankoFrontendSdk.Hanko("http://localhost:3000")
    ...
</script>

Options

You can pass certain options, when creating a new Hanko instance:

const defaultOptions = {
  timeout: 13000,           // The timeout (in ms) for the HTTP requests.
  cookieName: "hanko",      // The cookie name under which the session token is set.
  localStorageKey: "hanko"  // The prefix / name of the localStorage keys.
};
const hanko = new Hanko("http://localhost:3000", defaultOptions);

Documentation

To see the latest documentation, please click here.

Exports

SDK

  • Hanko - A class that bundles all functionalities.

Client Classes

  • UserClient - A class to manage users.
  • ThirdPartyClient - A class to handle social logins.
  • TokenClient - A class that handles the exchange of one time tokens for session JWTs.

Utility Classes

  • WebauthnSupport - A class to check the browser's WebAuthn support.

DTO Interfaces

  • PasswordConfig
  • EmailConfig
  • AccountConfig
  • Config
  • WebauthnFinalized
  • TokenFinalized
  • UserInfo
  • Me
  • Credential
  • User
  • UserCreated
  • Passcode
  • WebauthnTransports
  • Attestation
  • Email
  • Emails
  • WebauthnCredential
  • WebauthnCredentials
  • Identity

Event Interfaces

  • SessionDetail

Event Types

  • CustomEventWithDetail
  • sessionCreatedType
  • sessionExpiredType
  • userLoggedOutType
  • userDeletedType

Error Classes

  • HankoError
  • TechnicalError
  • ConflictError
  • RequestTimeoutError
  • WebauthnRequestCancelledError
  • InvalidPasswordError
  • InvalidPasscodeError
  • InvalidWebauthnCredentialError
  • PasscodeExpiredError
  • MaxNumOfPasscodeAttemptsReachedError
  • NotFoundError
  • TooManyRequestsError
  • UnauthorizedError

Examples

Get the current user / Validate the JWT against the Hanko API

The Hanko API issues a JWT when a user logs in. For certain actions, like obtaining the user object, a valid JWT is required. The following example shows how to get the user object of the current user, or to identify that the user is not logged in:

import { Hanko, UnauthorizedError } from "@teamhanko/hanko-frontend-sdk"

const hanko = new Hanko("https://[HANKO_API_URL]")

try {
    const user = await hanko.user.getCurrent()

    // A valid JWT is in place so that the user object was able to be fetched.
} catch (e) {
    if (e instanceof UnauthorizedError) {
        // Display an error or prompt the user to login again. After a successful call to `hanko.webauthn.login()`,
        // `hanko.password.login()` or `hanko.passcode.finalize()` a JWT will be issued and `hanko.user.getCurrent()`
        // would succeed.
    }
}

Custom Events

You can bind callback functions to different custom events. The callback function will be called when the event happens and an object will be passed in, containing event details. The event binding works as follows:

// Controls the optional `once` parameter. When set to `true` the callback function will be called only once.
const once = false;

const removeEventListener = hanko.onSessionCreated((eventDetail) => {
    // Your code...
}, once);

The following events are available:

  • "hanko-session-created": Will be triggered after a session has been created and the user has completed possible additional steps (e.g. passkey registration or password recovery). It will also be triggered when the user logs in via another browser window. The event can be used to obtain the JWT. Please note, that the JWT is only available, when the Hanko API configuration allows to obtain the JWT. When using Hanko-Cloud the JWT is always present, for self-hosted Hanko-APIs you can restrict the cookie to be readable by the backend only, as long as your backend runs under the same domain as your frontend. To do so, make sure the config parameter "session.enable_auth_token_header" is turned off via the Hanko-API configuration. If you want the JWT to be contained in the event details, you need to turn on "session.enable_auth_token_header" when using a cross-domain setup. When it's a same-domain setup you need to turn off "session.cookie.http_only" to make the JWT accessible to the frontend.
hanko.onSessionCreated((sessionDetail) => {
  // A new JWT has been issued.
  console.info(`Session created or updated (user-id: "${sessionDetail.userID}", jwt: ${sessionDetail.jwt})`);
})
  • "hanko-session-expired": Will be triggered when the session has expired, or when the session has been removed in another browser window, because the user has logged out, or deleted the account.
hanko.onSessionExpired(() => {
  // You can redirect the user to a login page or show the `<hanko-auth>` element, or to prompt the user to log in again.
  console.info("Session expired");
})
  • "hanko-user-logged-out": Will be triggered, when the user actively logs out. In other browser windows, a "hanko-session-expired" event will be triggered at the same time.
hanko.onUserLoggedOut(() => {
  // You can redirect the user to a login page or show the `<hanko-auth>` element.
  console.info("User logged out");
})
  • "hanko-user-deleted": Will be triggered when the user has deleted the account. In other browser windows, a "hanko-session-expired" event will be triggered at the same time.
hanko.onUserDeleted(() => {
  // You can redirect the user to a login page or show the `<hanko-auth>` element.
  console.info("User has been deleted");
})

Please Take a look into the docs for more details.

Bugs

Found a bug? Please report on our GitHub page.

License

The hanko-frontend-sdk project is licensed under the MIT License.