React & Go Quickstart

This is a quickstart guide to help you integrate Descope with your React & Go application. Follow the steps below to get started.

Install Frontend SDK

Install the SDK with the following command:

Terminal
npm i --save @descope/react-sdk

Import Frontend SDK

Next step is to import all of the built-in functions you will want to use from Descope React SDK.

App.js
import { useDescope, useSession, useUser } from '@descope/react-sdk'
import { Descope } from '@descope/react-sdk'
import { getSessionToken } from '@descope/react-sdk';

Wrap Application with AuthProvider

Wrap the entire application with <AuthProvider />. You need your Project ID for this step, which you can take from the snippet on the right.

Note

You can also add the optional baseUrl parameter if you're utilizing a CNAME within your Descope project (ex: https://auth.company.com).

index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { AuthProvider } from '@descope/react-sdk';
 
import App from './App';
 
const root = ReactDOM.createRoot(document.getElementById('root'));
 
root.render(
    <React.StrictMode>
        <AuthProvider projectId='__ProjectID__'>
            <App />
        </AuthProvider>
    </React.StrictMode>
);

Add Flows Component

To trigger the Descope Flow, you will need to add this component. The screens you've customized in your Flow will appear here. You can also customize the component with the following:

  • flowId - ID of the flow you wish to use
  • onSuccess and onError - functions that execute when authentication succeeds or fails
  • onReady - event that is triggered when flow is ready to be displayed. This is useful for showing a loading indication before the page is ready. This is a boolean that you can pass in with useState().
  • theme - "light" or "dark", the default is "light"
  • debug - a boolean that shows a debug widget if true, default is false
  • tenant - this is where you put the <tenant ID> of the tenant you wish to use in the authentication flow.
  • redirectUrl - Redirect URL for OAuth and SSO (will be used when redirecting back from the OAuth provider / IdP), or for "Magic Link" and "Enchanted Link" (will be used as a link in the message sent to the the user). When configured within the flow, it overrides the configuration within the Descope console.
  • validateOnBlur - a boolean to configure whether field validation is performed when clicking away from the field (true) or on form submission (false)
  • form - You can optionally pass flow inputs, such as email addresses, names, etc., from your app's frontend to your flow. The configured form inputs can be used within flow screens, actions, and conditionals prefixed with form.
    • Ex: form={{ email: "predefinedname@domain.com", firstName: "test", "customAttribute.test": "aaaa", "myCustomInput": 12 }}
  • client - You can optionally pass flow inputs from your app's frontend to your flow. The configured client inputs can be used within flow actions and conditionals prefixed with client..
    • Ex: client={{ version: "1.2.0" }}

Note

Descope stores the last user information in local storage. If you wish to disable this feature, you can pass storeLastAuthenticatedUser as false to the AuthProvider component. Please note that some features related to the last authenticated user may not function as expected if this behavior is disabled.

App.js
import { useDescope, useSession, useUser } from '@descope/react-sdk'
import { Descope } from '@descope/react-sdk'
import { getSessionToken } from '@descope/react-sdk';
 
const App = () => {
	return (
		<Descope
          flowId="sign-up-or-in"
          onSuccess={(e) => console.log(e.detail.user)}
          onError={(e) => console.log('Could not log in!')}
        />
	);
};

Getting User Details

To extract details on the user, you can load the user details from e.detail.user. On successful authentication, the information about the user is returned and accessible with e.detail.user.

  • onSuccess - function that executes when authentication succeeds

Example:

App.js
import { useDescope, useSession, useUser } from '@descope/react-sdk'
import { Descope } from '@descope/react-sdk'
import { getSessionToken } from '@descope/react-sdk';
 
const App = () => {
	return (
		<Descope
			flowId="sign-up-or-in"
			// get user details inside the onSuccess function
			onSuccess={(e) => {
				console.log(e.detail.user.name);
				console.log(e.detail.user.email);
			}}
			redirectAfterSuccess="/"
		/>
	);
};

Alternatively, you can also use the me function which fetches the current authenticated user information.

Utilize the React SDK Hooks and Functions

Descope provides many different hooks to check if the user is authenticated, session is loading etc. You can use these to customize the user experience:

  • isAuthenticated: is user authenticated?
  • isSessionLoading: This is used for implementing loading screens while sessions are being established
  • user: user object that contains all user attributes (email, name, etc.)
  • isUserLoading: This is used for implementing loading screens while user objects are being loaded
  • getSessionToken(): This gets the session token from your browser which you can include in your backend requests
App.js
import { useCallback } from 'react'
 
import { useDescope, useSession, useUser } from '@descope/react-sdk'
import { Descope } from '@descope/react-sdk'
import { getSessionToken } from '@descope/react-sdk';
 
const App = () => {
  const { isAuthenticated, isSessionLoading } = useSession()
  const { user, isUserLoading } = useUser()
  const { logout } = useDescope()
 
  const exampleFetchCall = async () => {
    const sessionToken = getSessionToken();
 
    // example fetch call with authentication header
    fetch('your_application_server_url', {
      headers: {
        Accept: 'application/json',
        Authorization: 'Bearer ' + sessionToken,
      }
    })
  }
 
  const handleLogout = useCallback(() => {
    logout()
  }, [logout])
 
  return <>
    {!isAuthenticated &&
      (
        <Descope
          flowId="sign-up-or-in"
          onSuccess={(e) => console.log(e.detail.user)}
          onError={(e) => console.log('Could not log in!')}
        />
      )
    }
 
    {
      (isSessionLoading || isUserLoading) && <p>Loading...</p>
    }
 
    {!isUserLoading && isAuthenticated &&
      (
        <>
          <p>Hello {user.name}</p>
          <div>My Private Component</div>
          <button onClick={handleLogout}>Logout</button>
        </>
      )
    }
  </>;
}
 
export default App;

At this point, you're done with the frontend. If you would like to also handle Session Management in your backend, keep on reading!

Install Backend SDK

Install the SDK with the following command:

Terminal
go get github.com/descope/go-sdk

Import and Setup Backend SDK

You'll need import and setup all of the packages from the SDK.

If you're using a CNAME with your Descope project, make sure to include BaseUrl as a parameter in your client.Config (e.g. {BaseUrl : "https://api.descope.com"}) when initializing descopeClient.

app.go
import "github.com/descope/go-sdk/descope"
import "github.com/descope/go-sdk/descope/client"
 
// Utilizing the context package allows for the transmission of context capabilities like cancellation
//      signals during the function call. In cases where context is absent, the context.Background()
//      function serves as a viable alternative.
//      Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
import (
	"context"
)

Implement Session Validation

You will need to then fetch the session token from the Authorization header of each request, and use the SDK to validate the token.

The frontend SDK will store the session token in either a cookie or your browser's local storage. If using a cookie, the token will be sent to your app server automatically with every request.

app.go
descopeClient, err := client.NewWithConfig(&client.Config{ProjectID:"__ProjectID__"})
if err != nil {
    log.Println("failed to initialize: " + err.Error())
}
 
// ctx: context.Context - Application context for the transmission of context capabilities like
//        cancellation signals during the function call. In cases where context is absent, the context.Background()
//        function serves as a viable alternative.
//        Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
ctx := context.Background()
 
// Fetch session token from HTTP Authorization Header
sessionToken := "xxxx"
 
authorized, userToken, err := descopeClient.Auth.ValidateSessionWithToken(ctx, sessionToken)
if (err != nil){
  fmt.Println("Could not validate user session: ", err)
} else {
  fmt.Println("Successfully validated user session: ", userToken)
}

Congratulations

Now that you've got the authentication down, go focus on building out the rest of your app!


Checkpoint

Your application is now integrated with Descope. Please test with sign-up or sign-in use case.

Need help?

Customize

Now that you have the end-to-end application working, you can choose to configure and personalize many different areas of Descope, including your brand, style, custom user authentication journeys, etc. We recommend starting with customizing your user-facing screens, such as signup and login.

Was this helpful?

On this page