New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@descope/react-sdk

Package Overview
Dependencies
Maintainers
4
Versions
619
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@descope/react-sdk

Descope React SDK

  • 0.0.52-alpha.22
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
34K
increased by4.17%
Maintainers
4
Weekly downloads
 
Created
Source

@descope/react-sdk

This library lets you consume your login pages created by Descope console-app in your application Under the hood, it uses web-js-sdk

Usage

Install the package

npm install @descope/react-sdk

Render it in your application

Wrap your app with Auth Provider
import { AuthProvider } from '@descope/react-sdk';

const AppRoot = () => {
	return (
		<AuthProvider projectId="myProjectId">
			<App />
		</AuthProvider>
	);
};
Use Descope to render specific flow

You can use default flows or provide flow id directly to the Descope component

1. Default flows
import { SignInFlow } from '@descope/react-sdk'
// you can choose flow to run from the following
// import { SignUpFlow } from '@descope/react-sdk'
// import { SignUpOrInFlow } from '@descope/react-sdk'

const App = () => {
    return (
        {...}
        <SignInFlow
            onSuccess={(e) => console.log('Logged in!')}
            onError={(e) => console.log('Could not logged in!')}
        />
    )
}
2. Provide flow id
import { Descope } from '@descope/react-sdk'

const App = () => {
    return (
        {...}
        <Descope
            flowId="myFlowId"
            onSuccess={(e) => console.log('Logged in!')}
            onError={(e) => console.log('Could not logged in!')}
            // theme can be "light" or "dark". If empty, Descope will use the OS theme
            // theme="light"
        />
    )
}
Use the useAuth hook in your components in order to access authentication state and utilities

This can be helpful to implement application-specific logic. Examples:

  • Render different components if current session is authenticated
  • Render user's content
  • Logout button
import { useAuth } from '@descope/react-sdk'

const App = () => {
    // NOTE - `useAuth` should be used inside `AuthProvider` context,
    // and will throw an exception if this requirement is not met
    const { authenticated, user, logout } = useAuth()
    return (
        {...}
        {
            // render different components if current session is authenticated
            authenticated && <MyPrivateComponent />
        }
        {
            // render user's content
            authenticated && <div>Hello ${user.name}</div>
        }
        {
            // logout button
            authenticated && <button onClick={logout}>Logout</div>
        }
    )
}
Session token server validation (pass session token to server API)

When developing a full-stack application, it is common to have private server API which requires a valid session token:

session-token-validation-diagram

Note: Descope also provides server-side SDKs in various languages (NodeJS, Go, Python, etc). Descope's server SDKs have out-of-the-box session validation API that supports the options described bellow. To read more about session validation, Read this section in Descope documentation.

The mechanism to pass session token depends on the Descope project's "Token response method" configuration.

1. Manage in cookies
  • Descope sets session token as cookie, which automatically sent each server api request. This option is more secure and is the recommended method for managing tokens, but for this option to work well with the browser - you must also configure a CNAME record for the custom domain listed, which will give a unified log in experience and securely restrict access to the session tokens that are stored in the cookies.

When this option is configured, the browser will automatically add the session token cookie to the server in every request.

2. Manage in response body
  • Descope API returns session token in body. In this option, The React application should pass session cookie (const { sessionToken } = useAuth()) as Authorization header. This option never requires a custom domain, and is recommended for testing or while working in a sandbox environment.

An example for using session token,

import { useAuth } from '@descope/react-sdk'
import { useCallback } from 'react'

const App = () => {
    const { sessionToken } = useAuth()

    const onClick = useCallback(() => {
        fetch('https://localhost:3002/api/some-path' {
            method: 'GET',
            headers: { Authorization: `Bearer ${sessionToken}` }
        })
    },[sessionToken])
    return (
        {...}
        {
            // button that triggers an API that may use session token
            <button onClick={onClick}>Click Me</div>
        }
    )
}

Run a local example

There is a simple app that uses Descope React SDK, with two routes

  • Home
  • Login

In order to run this app locally, do the following steps:

  • Clone this repository
  • Navigate to repository directory
  • Run npm i
  • Create a .env file with the following variables (or alternatively export them manually):
// .env
# Your project id
DESCOPE_PROJECT_ID=<project-id>
# Flow id to run, e.g. sign-up-or-in
DESCOPE_FLOW_ID=<flow-id>
# Optional - Descope base url, e.g. http://localhost:8000
DESCOPE_BASE_URL=<base-url>
  • Run npm run start
  • Go to http://localhost:3000/ and press the "Start Flow" button

Note: if you change env file (for example, change DESCOPE_PROJECT_ID), you need to rerun npm run start

FAQs

Package last updated on 01 Dec 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc