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

@headstorm/react-auth

v1.3.3

Published

OAuth2 + OpenID connect client library for React with support for authorization code flow with PKCE

Downloads

3

Readme

React Auth

OAuth2 + OpenID connect client library for React with support for authorization code flow with PKCE.

Getting Started

  1. Wrap your application in an AuthProvider with the config of your auth server. You can optionally include an AuthGuard which prevents unauthenticated access to any page on your app expect for those explicitly listed.
// pages/_app.tsx
export type ChildrenProp = { children: ReactNode }

const AdminAuth: React.FC<ChildrenProp> = ({ children }) => {
  const router = useRouter()

  const appUrl = process.env.NEXT_PUBLIC_APP_URL
  const tenantId = process.env.NEXT_PUBLIC_TENANT_ID

  const baseAuthUri = `https://login.microsoftonline.com/${tenantId}`

  return (
    <AuthProvider
      authority={baseAuthUri}
      clientId={process.env.NEXT_PUBLIC_CLIENT_ID as string}
      redirectUri={`${appUrl}/login/callback`}
      postLogoutRedirectUri={`${appUrl}/logout/success`}
      scope={`openid profile email offline_access YOUR_CUSTOM_SCOPES`}
      cacheStrategy="localStorage"
    >
      <AuthGuard
        whitelistedPaths={[
          '/login',
          '/login/callback',
          '/logout/success',
          '/logout',
        ]}
        currentPathName={router.pathname}
      >
        {children}
      </AuthGuard>
    </AuthProvider>
  )
}

This example uses Next.js as a React framework and Azure AD as the OAuth server, but the same pattern applies regardless of Next.js or OAuth server.

  1. Create your /login/callback page to handle exchanging the authorization code for an access token.
// pages/login/callback.tsx
const AuthCallback: React.FC = () => {
  const callbackError = useAuthCallback()
  const { redirectToLogin } = useAuth()

  if (!callbackError) {
    return null
  }

  return (
    <p>
      Login error - {callbackError.error} - {callbackError.errorDescription}
      <button type="button" onClick={() => redirectToLogin()}>
        Login
      </button>
    </p>
  )
}

export default AuthCallback

The useAuthCallback() hook will automatically look for the authorization code in the URL, exchange it for an access token, and redirect the user to their original destination.

  1. Create a logout success page that the user should be redirected to once they've successfully logged out.
const LogoutSuccess: React.FC = () => {
  const { isAuthenticated, isLoading } = useAuth()
  const router = useRouter()

  useEffect(() => {
    if (isAuthenticated) {
      router.push('/')
    }
  }, [isAuthenticated, router])

  if (!isLoading && !isAuthenticated) {
    return <p>You've been logged out!</p>
  }

  return null
}
  1. The user is successfully authenticated! You can retrieve the access token by invoking the getAccessTokenSilently() function returned by the useAuth() hook.

Example using Apollo Client:

export const AuthorizedApolloProvider: React.FC<Props> = ({ children }) => {
  const { isAuthenticated, getAccessTokenSilently } = useAuth()
  const client = useMemo(() => {
    const httpLink = createHttpLink({
      uri: process.env.NEXT_PUBLIC_GRAPHQL_URL,
    })

    const authLink = setContext(async () => {
      if (!isAuthenticated) {
        return {}
      }

      const token = await getAccessTokenSilently()
      return {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      }
    })

    return new ApolloClient({
      link: authLink.concat(httpLink),
      cache: new InMemoryCache(),
    })
  }, [isAuthenticated, getAccessTokenSilently])

  return <ApolloProvider client={client}>{children}</ApolloProvider>
}
  1. Optionally setup /login and /logout pages that redirects the user into the appropriate login/logout flows.
// pages/login/index.tsx
const Login: React.FC = () => {
  const { isAuthenticated, redirectToLogin, isLoading } = useAuth()
  const router = useRouter()

  useEffect(() => {
    if (isLoading) {
      return
    }

    if (isAuthenticated) {
      router.push('/')
      return
    }

    redirectToLogin({
      loginSuccessRedirectUri: '/',
    })
  }, [isAuthenticated, isLoading, redirectToLogin, router])

  return null
}
// pages/logout/index.tsx
const Logout: React.FC = () => {
  const { isAuthenticated, redirectToLogout, isLoading } = useAuth()
  const router = useRouter()

  useEffect(() => {
    ;(async () => {
      if (isLoading) {
        return
      }

      if (isAuthenticated) {
        await redirectToLogout()
        return
      }

      await router.push('/logout/success')
    })()
  }, [isAuthenticated, isLoading, redirectToLogout, router])

  return null
}