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

@userdocks/react-sdk

v0.6.1

Published

The React SDK for userdocks. Securly store, access, and refresh access tokens in your React app.

Downloads

14

Readme

@userdocks/react-sdk

npm GitHub Workflow Status Coveralls branch NPM

The React web client SDK for userdocks. Securly store, access, and refresh access tokens in your React application.

Table of Contents

Install

npm i @userdocks/react-sdk

Methods

Documentation of all the functions and methods this SDK exposes.

UserdocksProvider

Syntax

import { UserdocksProvider } from '@userdocks/react-sdk';

render(
  <UserdocksProvider options={options}>
    {children}
  </UserdocksProvider>
);

Parameters

  • options <object>: an object holding two key value pairs
    • authServer <object | undefined>: an object holding four key value pairs
      • domain <string | undefined>: the domain of the authetication server (optional)
      • apiUri <string | undefined>: the uri of the api of the authetication server (optional)
      • paymentUri <string | undefined>: the uri of the payment page of the authetication server (optional)
      • loginUri <string | undefined>: the uri of the login page of the authetication server (optional)
      • sdkUri <string | undefined>: the uri of the SDK of the authetication server (optional)
    • app <object>: an object holding three key value pairs
      • refreshType: <'silentRefresh' | 'refresh'>: How to refresh your authorization tokens (optional)
        • silentRefresh: uses cookies and an iframe for refreshing the tokens (authServer is required with this option)
        • refresh: uses the localStorage or sessionStorage (only for the refresh token, the access token is only stored in memory) and an HTTP request to refresh the tokens (default value)
      • origin <string>: the uri of the client application (required)
      • clientId <string>: the UUID of an userdocks application (required)
      • redirectUri <string>: the redirect uri of the userdocks application (required)

useUserdocks

This custom hook returns an object.

It can be used in function components.

Syntax

This is a custom hook to get the current userdocks object from a UserdocksProvider.

import { useUserdocks } from '@userdocks/react-sdk';

function MyComponent() {
  const { isAuthenticated, userdocks } = useUserdocks();
  console.log('Is user authenticated: ', isAuthenticated)

  // ...
}

Return Value

  • identity <object>
    • isAuthenticated <boolean | null>: indicating if the user is autheticated after the token is initialized (is null if not initialized)
    • userdocks <object | null>: an object holding the @userdocks/web-client-sdk

Usage

Wrap your app with a UserdocksProvider:

import { UserdocksProvider } from '@userdocks/react-sdk';

const options = {
  // e.g. if using a cname
  authServer: {
    domain: `<domain-of-the-auth-server>`
    apiUri: '<the-payment-uri-of-your-application>',
    paymentUri: '<the-payment-uri-of-your-application>',
    loginUri: '<the-payment-uri-of-your-application>',
    sdkUri: '<the-payment-uri-of-your-application>',
  },
  app: {
    refreshType: '<refresh> or <silentRefresh>'
    origin: '<the-uri-of-your-application>',
    clientId: '<an-uuid-of-an-application-on-uderdocks>',
    redirectUri: '<the-redirect-uri-of-your-application>',
  },
};

render(
  <UserdocksProvider options={options}>
    <App />
  </UserdocksProvider>
);

Exchange the code to a token on your redirect uri:

import { useEffect, FC } from 'react';
import { useHistory } from 'react-router-dom';
import { useUserdocks } from '@userdocks/react-sdk';

const Callback = () => {
  const { is, userdocks } = useUserdocks();
  const history = useHistory();

  useEffect(() => {
    (async () => {
      try {
        // its better to initialize userdocks way up the tree
        // e.g. once in your App Component
        // userdocks should only be initialized once
        if (!isInitialized()) {
          await userdocks.initialize();
        }

        // for a exchange we do not need to check if it isAuthenticated
        const isLoginSuccess = await userdocks.exchangeCodeForToken();

        if (isLoginSuccess) {
          history.replace('/autheticated-component');
        } else {
          userdocks.redirectTo({ type: 'signIn' });
        }
      } catch (e) {
        console.error(e);

        // handle error or redirect to sign in page
        // if (userdocks) {
        //   userdocks.redirectTo({ type: 'signIn' });
        // }
      }
    })();
  }, [isLoading, userdocks]);

  return null;
};

export default Callback;

Check if a user is autheticated on any component:

import { useEffect, FC } from 'react';
import { useHistory } from 'react-router-dom';
import useUserdocks from '@userdocks/react-sdk';

const AnyComponent = () => {
  const { isAuthenticated, userdocks } = useUserdocks();
  const history = useHistory();

 // Example API Call to your server
  useEffect(() => {
    (async () => {
      // its better to initialize userdocks way up the tree
      // e.g. once in your App Component
      // userdocks should only be initialized once
      if (!isInitialized()) {
        await userdocks.initialize();
      }

      const token = await userdocks.getToken({ refresh: true });

      if (!token.accessToken) {
        userdocks.redirectTo({
          type: 'unauthenticated',
        });
      }

      if (token.tokenType && token.accessToken) {
        try {
          const response = await fetch('https://example.api.com/v1/users', {
            headers: {
              'Authorization': `${token.tokenType} ${token.accessToken}`,
            },
          });

          const data = await response.json();

          // do something with the data
        } catch(err) {
          // handle error
        }
      }
    })();
  }, [isAuthenticated]);

  if (userdocks.isInitialized() && isAuthenticated === false) {
    userdocks.redirectTo({
      type: 'unauthenticated',
    });

    return null;
  }

  return <div>Is Autheticated</div>;
};

export default AnyComponent;