### Build and Run Descope React SDK Examples Source: https://github.com/descope/descope-js/blob/main/packages/sdks/react-sdk/README.md Commands to install project dependencies and start the Descope React SDK example application. It notes a prerequisite about modifying the `tsconfig.json` file to ensure the examples are included in the build process. ```bash npm i && npm start ``` -------------------------------- ### Run Descope Vue SDK Example Application Source: https://github.com/descope/descope-js/blob/main/packages/sdks/vue-sdk/README.md Commands to install necessary dependencies and start the Descope Vue SDK example application. After execution, the application will be accessible in a web browser at `http://localhost:3000`. ```bash npm i && npm start ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/examples/pages-router/README.md This command installs all necessary Node.js packages and dependencies required for the Next.js Descope example application. It ensures that all project requirements are met before running the application. ```bash npm install ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/examples/app-router/README.md Installs all necessary Node.js packages and project dependencies defined in 'package.json' for the current project. ```bash npm install ``` -------------------------------- ### Run Next.js Descope Example Application Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/examples/pages-router/README.md This command starts the Next.js development server, making the Descope example application accessible locally. Once running, you can open the specified URL in your browser to interact with the application. ```bash npm run dev ``` -------------------------------- ### Install Descope Web Component Package Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-component/README.md Instructions on how to install the `@descope/web-component` package using npm, which is the first step to integrate the library into your project. ```bash npm install @descope/web-component ``` -------------------------------- ### Build and Run Descope Demo Angular Application Source: https://github.com/descope/descope-js/blob/main/packages/sdks/angular-sdk/README.md Provides the command-line instruction to install project dependencies and then start the Descope demo Angular application. This is typically run from the root directory of the project. ```bash pnpm i && npm start ``` -------------------------------- ### Example .env File Configuration for Descope JS SDK Source: https://github.com/descope/descope-js/blob/main/packages/sdks/react-sdk/README.md Demonstrates how to configure optional environment variables for the Descope JS SDK example application using a .env file. This includes project ID, flow IDs, base URLs, theme, locale, redirect URLs, tenant ID, debug mode, step-up flow, and telemetry key, providing a template for quick setup. ```dotenv # Your project ID DESCOPE_PROJECT_ID="" # Login flow ID DESCOPE_FLOW_ID="" # Descope base URL DESCOPE_BASE_URL="" # Descope base static URL DESCOPE_BASE_STATIC_URL="" # Set flow theme to dark DESCOPE_THEME=dark # Set flow locale, default is browser's locale DESCOPE_LOCALE="" # Flow Redirect URL DESCOPE_REDIRECT_URL="" # Tenant ID DESCOPE_TENANT_ID="" # Enable debugger DESCOPE_DEBUG_MODE=true # Show step-up flow for logged in user DESCOPE_STEP_UP_FLOW_ID=step-up # Telemetry key DESCOPE_TELEMETRY_KEY="" ``` -------------------------------- ### Build Descope SDK Package Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/examples/app-router/README.md Navigates to the parent directory and builds the Descope SDK package using npm, a prerequisite for running the example. ```bash (cd ../../ && npm run build) ``` -------------------------------- ### Install Descope Web JS SDK Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-js-sdk/README.md Instructions to install the Descope Web JavaScript SDK using npm, the package manager for Node.js. ```bash npm install @descope/web-js-sdk ``` -------------------------------- ### Configure Environment Variables for Descope Example Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-component/README.md Details the necessary environment variables to be set in a `.env` file for running the Descope web component example. These variables include the Descope Project ID, Flow ID, optional Base URL, and Locale. ```env // .env # Descope Project ID DESCOPE_PROJECT_ID= # Flow ID to run, e.g. sign-up-or-in DESCOPE_FLOW_ID= # Optional - Descope base URL DESCOPE_BASE_URL # Optional - Descope locale (according to the target locales configured in the flow) DESCOPE_LOCALE= ``` -------------------------------- ### Install Descope Core JS SDK Source: https://github.com/descope/descope-js/blob/main/packages/sdks/core-js-sdk/README.md This command installs the `@descope/core-js-sdk` package using npm, the package manager for JavaScript. It's the first step to integrate the Descope SDK into your project. ```bash npm install @descope/core-js-sdk ``` -------------------------------- ### Build Descope SDK Package Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/examples/pages-router/README.md This command navigates to the parent directory and builds the Descope SDK package. It's a prerequisite step to ensure the SDK is compiled and ready for use within the example application. ```bash (cd ../../ && npm run build) ``` -------------------------------- ### Install Descope React SDK Source: https://github.com/descope/descope-js/blob/main/packages/sdks/react-sdk/README.md This snippet demonstrates how to install the Descope React SDK package using npm, adding it as a dependency to your project. ```bash npm i --save @descope/react-sdk ``` -------------------------------- ### Initialize Descope Plugin and Get SDK Instance in Vue Source: https://github.com/descope/descope-js/blob/main/packages/sdks/vue-sdk/README.md This example demonstrates how to initialize the Descope Vue plugin with a project ID and then retrieve the SDK instance using `getSdk()`. It also shows how to subscribe to session token and authentication state changes using `onSessionTokenChange` and `onIsAuthenticatedChange` callbacks. ```javascript import { createApp } from 'vue'; import App from './components/App.vue'; import descope, { getSdk } from '../src'; const app = createApp(App); app.use(descope, { projectId: 'project-id', }); const sdk = getSdk(); sdk?.onSessionTokenChange((newSession) => { // here you can implement custom logic when the session is changing, // note that the session may be not available if it is managed in cookies }); sdk?.onIsAuthenticatedChange((isAuthenticated) => { // here you can implement custom logic when the authentication state is changing }); ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/examples/app-router/README.md Launches the Next.js development server, making the application accessible locally for testing and development purposes. ```bash npm run dev ``` -------------------------------- ### Install Descope Vue SDK via npm Source: https://github.com/descope/descope-js/blob/main/packages/sdks/vue-sdk/README.md Installs the `@descope/vue-sdk` package using npm, adding it as a project dependency. This is the first step to integrate Descope authentication into a Vue application. ```bash npm i --save @descope/vue-sdk ``` -------------------------------- ### Install Descope Next.js SDK via npm Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/README.md This snippet shows how to install the Descope Next.js SDK using npm, saving it as a dependency in your project. This is the first step to integrate Descope authentication into your Next.js application. ```bash npm i --save @descope/nextjs-sdk ``` -------------------------------- ### Configure Descope Environment Variables Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/examples/pages-router/README.md This snippet provides the essential environment variables needed to connect the Next.js application with your Descope project. It includes placeholders for your Descope Project ID, Flow ID, and Management Key, along with an example for a custom sign-in route. ```bash NEXT_PUBLIC_DESCOPE_PROJECT_ID= NEXT_PUBLIC_DESCOPE_FLOW_ID= DESCOPE_MANAGEMENT_KEY= # Default is sign-up-or-in # This is an example of a custom route for the sign-in page # the /login route is the one that this example uses SIGN_IN_ROUTE="/login" ``` -------------------------------- ### Descope JS SDK Multi-Step Authentication Flow Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-js-sdk/examples/stepup/index.html This JavaScript code implements a sequential authentication process using the Descope SDK. It guides a user through steps like initializing the SDK with a project ID, signing up/in with email OTP, updating and verifying a phone number via SMS OTP, and performing a step-up authentication. The script dynamically updates a simple HTML form to prompt the user for input at each stage. ```javascript let sdk; let step = 0; let mail; let token; let phone; const fns = [ (projectId) => { sdk = Descope({ projectId }); }, (email) => { mail = email; return sdk.otp.signUpOrIn.email(email); }, async (code) => { resp = await sdk.otp.verify.email(mail, code); token = resp.data.refreshJwt; }, (p) => { phone = p; sdk.otp.update.phone.sms(mail, phone, token); }, (code) => { sdk.otp.verify.sms(mail, code); // we are starting here a new signin process, to demonstrate stepup sdk.otp.signUpOrIn.email(mail); }, async (code) => { // get a jwt for the first validation of the signin resp = await sdk.otp.verify.email(mail, code); token = resp.data.refreshJwt; // Now automatically start a stepup process with the phone sdk.otp.signIn.sms( mail, { stepup: true, customClaims: { demo: 'pageName' } }, token, ); }, (code) => sdk.otp.verify.sms(mail, code), ]; const texts = [ "What's your email?", "What's the code you got in your email?", 'Lets add your phone as well', "What's the code you got via sms?", 'We started the sign in again with the same email as before\\nwhat code did you get now?', 'What is the code you got to the phone provided before ?', 'Success!', ]; const formEle = document.getElementsByTagName('form')[0]; const h1Ele = document.getElementsByTagName('h1')[0]; const inputEle = document.getElementsByTagName('input')[0]; formEle.onsubmit = async function (e) { e.preventDefault(); const input = new FormData(e.target).get('input'); let resp; try { resp = await fns[step](input); if (resp?.ok === false) alert(JSON.stringify(resp, null, 4)); } catch (e) { alert(e.message); return; } h1Ele.innerText = texts[step]; inputEle.value = ''; step++; if (!texts[step]) { formEle.remove(); alert(JSON.stringify(resp, null, 4)); } }; ``` -------------------------------- ### Descope SAML Multi-Step Authentication Form (JavaScript) Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-js-sdk/examples/saml/index.html This JavaScript code implements a simple web form that guides a user through a Descope SAML authentication process. It first prompts for a Descope Project ID, then for an email or tenant identifier. Upon submission of the second step, it uses the Descope SDK's `saml.start` method to initiate the SAML flow and redirects the user to the generated authentication URL. The code handles form submission, state management for the multi-step process, and basic error alerting. ```javascript let sdk; let step = 0; let mail; let projId; const fns = [ (projectId) => { projId = projectId; sdk = Descope({ projectId }); }, (emailOrTenant) => { mail = emailOrTenant; const uri = new URL(window.location.href); uri.host = 'localhost'; // does not work with 127.0.0.1 for now uri.pathname += 'verify.html'; uri.searchParams.set('projectId', projId); return sdk.saml.start(emailOrTenant, uri.toString()).then((resp) => { window.location = resp.data.url; }); }, ]; const texts = ["What's your email/tenant?", 'Redirecting...']; const formEle = document.getElementsByTagName('form')[0]; const h1Ele = document.getElementsByTagName('h1')[0]; const inputEle = document.getElementsByTagName('input')[0]; formEle.onsubmit = async function (e) { e.preventDefault(); const input = new FormData(e.target).get('input'); try { const resp = await fns[step](input); if (resp?.ok === false) alert(JSON.stringify(resp, null, 4)); } catch (e) { alert(e.message); return; } h1Ele.innerText = texts[step]; inputEle.value = ''; step++; if (!texts[step]) formEle.remove(); }; ``` -------------------------------- ### Initialize and Use Descope Core JS SDK for OTP Sign-In Source: https://github.com/descope/descope-js/blob/main/packages/sdks/core-js-sdk/README.md This JavaScript example demonstrates how to import the `createSdk` function, initialize the Descope SDK with your project ID, and then use the `otp.signIn.email` method to initiate an email-based One-Time Password sign-in flow for a given login ID. ```js import createSdk from '@descope/core-js-sdk'; const projectId = ''; const sdk = createSdk({ projectId }); const loginId = 'loginId'; sdk.otp.signIn.email(loginId); ``` -------------------------------- ### Use Descope Web Component as a JavaScript Library Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-component/README.md Demonstrates how to import and render the Descope web component within a JavaScript application. This includes defining the custom element and an example of rendering it in a JSX context with a `project-id`. ```js import '@descope/web-component' // This import will define `descope-wc` custom element import { DescopeWc } // In case you need types definition or you want to use the class directly ``` ```js render(){ return ( ) } ``` -------------------------------- ### Install Descope Angular SDK via npm Source: https://github.com/descope/descope-js/blob/main/packages/sdks/angular-sdk/README.md This command installs the `@descope/angular-sdk` package and saves it as a dependency in your project. It's the first step to integrate Descope into your Angular application. ```bash npm i --save @descope/angular-sdk ``` -------------------------------- ### Example: Implementing `onScreenUpdate` for Custom Screen Logic Source: https://github.com/descope/descope-js/blob/main/packages/sdks/angular-sdk/README.md Illustrates a practical example of the `onScreenUpdate` function, showing how to conditionally return `true` to trigger custom screen rendering based on the `screenName`. ```javascript function onScreenUpdate(screenName, context, next, ref) { if (screenName === 'My Custom Screen') { return true; } return false; } ``` -------------------------------- ### Descope Next.js SDK: Server-Side SDK Initialization and Usage Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/README.md Demonstrates how to initialize the Descope SDK on the server-side using the `createSdk` function within a Next.js Route handler. It shows configuration options for `projectId` and `managementKey`, and an example of using the SDK to load user data. ```js // src/pages/api/routes.ts import { createSdk } from '@descope/nextjs-sdk/server'; const sdk = createSdk({ // The Descope project ID to use for authentication // Defaults to process.env.NEXT_PUBLIC_DESCOPE_PROJECT_ID projectId: 'your-descope-project-id', // The Descope management key to use for management operations // Defaults to process.env.DESCOPE_MANAGEMENT_KEY managementKey: 'your-descope-management-key' // Optional: Descope API base URL // Defaults to process.env.NEXT_PUBLIC_DESCOPE_BASE_URL // baseUrl: 'https://...' }); export async function GET(req) { const { searchParams } = new URL(req.url); const loginId = searchParams.get('loginId'); const { ok, data: user } = await sdk.management.user.load(loginId); if (!ok) { // ... } // Use the user data ... } ``` -------------------------------- ### Descope Vue SDK Example .env.local Template Source: https://github.com/descope/descope-js/blob/main/packages/sdks/vue-sdk/README.md A template for the `.env.local` file, providing optional environment variables to customize the example application's behavior. These variables include `VUE_APP_DESCOPE_FLOW_ID` for login flow, `VUE_APP_DESCOPE_BASE_URL` for custom Descope base URL, and `VUE_APP_DESCOPE_BASE_STATIC_URL` for custom static URL. ```bash # Your project ID VUE_APP_DESCOPE_PROJECT_ID="" # Login flow ID VUE_APP_DESCOPE_FLOW_ID="" # Descope base URL VUE_APP_DESCOPE_BASE_URL="" # Descope base static URL VUE_APP_DESCOPE_BASE_STATIC_URL="" ``` -------------------------------- ### Test Descope User Details API Route Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/examples/app-router/README.md Demonstrates how to test the '/api' route handler, which returns user details using the Descope Management SDK, by making a 'curl' request with an authorization token. ```bash curl -H "Authorization: Bearer " http://localhost:3000/api ``` -------------------------------- ### Initialize Descope SDK and Check User Login Status Source: https://github.com/descope/descope-js/blob/main/packages/widgets/access-key-management-widget/src/app/index.html Initializes the Descope Web SDK with project details and provides an asynchronous function to check if a user is logged in. It also verifies if the logged-in user possesses the 'Tenant Admin' role, which is crucial for determining access to the management widget. ```JavaScript import createSdk from '@descope/web-js-sdk'; const sdk = createSdk({ projectId: DESCOPE_PROJECT_ID, baseUrl: DESCOPE_BASE_URL, persistTokens: true, }); const getShouldLogin = async () => { const res = await sdk.me(); if (!res.ok) { console.log('User is not logged in'); return true; } const userRoles = res.data?.userTenants?.find( (tenant) => tenant.tenantId === DESCOPE_TENANT, )?.roleNames || []; if (!userRoles.includes('Tenant Admin')) { console.log( 'User is not tenant admin, continue as bound user, received roles:', userRoles, ); } return false; }; ``` -------------------------------- ### Exchange SAML Code using Descope JavaScript SDK Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-js-sdk/examples/saml/verify.html This snippet initializes the Descope SDK by extracting the 'projectId' from the current URL's query parameters. It then retrieves a 'code' parameter from the URL and uses the `sdk.saml.exchange` method to process it. The successful response is then displayed in an alert. ```javascript const urlSearchParams = new URLSearchParams(window.location.search); const projectId = urlSearchParams.get('projectId'); const code = urlSearchParams.get('code'); let sdk = Descope({ projectId }); sdk.saml.exchange(code).then((resp) => { alert(JSON.stringify(resp, null, 4)); }); ``` -------------------------------- ### Configure Descope Environment Variables Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/examples/app-router/README.md Sets up essential environment variables required for Descope integration, including project ID, flow ID, and management key. A custom sign-in route can also be defined. These variables are typically stored in a '.env' file. ```bash NEXT_PUBLIC_DESCOPE_PROJECT_ID= NEXT_PUBLIC_DESCOPE_FLOW_ID= DESCOPE_MANAGEMENT_KEY= # Default is sign-up-or-in # This is an example of a custom route for the sign-in page # the /login route is the one that this example uses SIGN_IN_ROUTE="/login" ``` -------------------------------- ### Example: Defining Public Routes in Next.js Middleware Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/README.md This example illustrates how to use the `publicRoutes` option within the Descope `authMiddleware` configuration. Routes listed here will not require authentication, allowing unauthenticated users to access them. Default public routes like `/sign-in` and `/sign-up` are automatically included. ```typescript const options = { publicRoutes: ['/home', '/about'] }; ``` -------------------------------- ### Integrate Descope Applications Portal Widget into HTML Source: https://github.com/descope/descope-js/blob/main/packages/widgets/applications-portal-widget/README.md An example demonstrating how to include the Descope Applications Portal Widget via a CDN script and integrate it into an HTML page, including a JavaScript snippet to handle logout events and reload the page. ```html // replace x.x.x with the latest release of the widget: https://www.npmjs.com/package/@descope/applications-portal-widget ``` -------------------------------- ### Initialize Descope SDK and Check User Login Status Source: https://github.com/descope/descope-js/blob/main/packages/widgets/applications-portal-widget/src/app/index.html This JavaScript code initializes the Descope Web SDK using a project ID and base URL, enabling token persistence. It defines an asynchronous function, `getShouldLogin`, which checks the current user's authentication status by calling `sdk.me()` and returns true if the user is not logged in. ```JavaScript import createSdk from '@descope/web-js-sdk'; const sdk = createSdk({ projectId: DESCOPE_PROJECT_ID, baseUrl: DESCOPE_BASE_URL, persistTokens: true, }); const getShouldLogin = async () => { const res = await sdk.me(); if (!res.ok) { console.log('User is not logged in'); return true; } return false; }; ``` -------------------------------- ### Perform Descope JS SDK OAuth Exchange Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-js-sdk/examples/oauth/exchange.html This snippet initializes the Descope JavaScript SDK with a project ID extracted from the URL. It then retrieves an authorization code from the URL and uses the SDK's `oauth.exchange` method to complete the OAuth flow, displaying the response in an alert. ```JavaScript const formEle = document.getElementsByTagName('form')[0]; const h1Ele = document.getElementsByTagName('h1')[0]; const inputEle = document.getElementsByTagName('input')[0]; const urlSearchParams = new URLSearchParams(window.location.search); const projectId = urlSearchParams.get('projectId'); const code = urlSearchParams.get('code'); const sdk = Descope({ projectId }); sdk.oauth.exchange(code).then((resp) => { alert(JSON.stringify(resp, null, 4)); }); ``` -------------------------------- ### Start OIDC Login with Redirect Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-js-sdk/README.md This code snippet shows how to initiate the OIDC login process by calling the `loginWithRedirect` method. This method redirects the user to the Descope OIDC login page. An optional `redirect_uri` can be specified to control where the user is sent after successful login. ```js await sdk.oidc.loginWithRedirect({ // By default, the login will redirect the user to the current URL // If you want to redirect the user to a different URL, you can specify it here redirect_uri: window.location.origin, }); ``` -------------------------------- ### Descope Next.js SDK: Access Key Management Widget Usage Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/README.md Provides examples for embedding the `AccessKeyManagement` widget to manage access keys. It shows how to configure the widget for both an administrator view (managing all tenant users' keys) and a user view (managing keys for the logged-in tenant's user). ```js import { AccessKeyManagement } from '@descope/nextjs-sdk'; { /* admin view: manage all tenant users' access keys */ } ; { /* user view: mange access key for the logged-in tenant's user */ } ; ``` -------------------------------- ### Manage Descope Flow State and Events in Vue Script Source: https://github.com/descope/descope-js/blob/main/packages/sdks/vue-sdk/README.md This Vue ` ``` ```html ``` -------------------------------- ### Configure Descope Widget Environment Variables Source: https://github.com/descope/descope-js/blob/main/packages/widgets/applications-portal-widget/README.md Instructions for setting up the `.env` file with necessary Descope configuration parameters such as base URL, project ID, widget ID, debug mode, and theme settings. ```shell DESCOPE_BASE_URL= # env base url DESCOPE_PROJECT_ID= # project ID DESCOPE_WIDGET_ID= # default: applications-portal-widget DEBUG_MODE= # "true" / "false", default: "false" DESCOPE_THEME= # "light" / "dark" / "os", default: "light" ``` -------------------------------- ### Handle Descope `error` Event Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-component/README.md The `error` event is fired by the `descope-wc` component when an error occurs during the authentication flow. The event detail contains the error object, allowing developers to display custom error messages or perform other error handling logic. This example shows an alert displaying the error message. ```javascript const descopeWcEle = document.getElementsByTagName('descope-wc')[0]; descopeWcEle.addEventListener('error', (e) => alert(`Error! - ${e.detail.errorMessage}`)); ``` -------------------------------- ### Implement Custom Screen Rendering with `onScreenUpdate` Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-component/README.md The `onScreenUpdate` function is invoked whenever the Descope flow's screen state changes. It receives `screenName`, `context`, `next` (to continue flow), and `ref` (to the `descope-wc` node). Returning `true` indicates a custom screen will be rendered, allowing for highly customized UIs. This example demonstrates rendering a custom form for a specific screen name and handling its submission to continue the flow. ```javascript function onScreenUpdate(screenName, context, next, ref) { if (screenName === 'My Custom Screen') { ref.innerHTML = `
`; ref.closest('form').addEventListener('submit', (e) => { e.preventDefault(); const formData = new FormData(e.target); const data = Object.fromEntries(formData.entries()); // replace with the button interaction id next('interactionId', data); }); return true; } return false; } const descopeWcEle = document.querySelector('descope-wc'); descopeWcEle.onScreenUpdate = onScreenUpdate; ``` -------------------------------- ### Integrate Descope Role Management Widget with Authentication Flow Source: https://github.com/descope/descope-js/blob/main/packages/widgets/role-management-widget/src/app/index.html This JavaScript code initializes the Descope Web SDK and implements a logic to check user login status and 'Tenant Admin' role. Based on the user's authentication and role, it dynamically renders either a Descope authentication flow ('sign-up-or-in') or the 'descope-role-management-widget'. It also includes support for a 'mock' query parameter to bypass authentication. ```JavaScript import createSdk from '@descope/web-js-sdk'; const sdk = createSdk({ projectId: DESCOPE_PROJECT_ID, baseUrl: DESCOPE_BASE_URL, persistTokens: true, }); const getShouldLogin = async () => { const res = await sdk.me(); if (!res.ok) { console.log('User is not logged in'); return true; } const userRoles = res.data?.userTenants?.find( (tenant) => tenant.tenantId === DESCOPE_TENANT, )?.roleNames || []; if (!userRoles.includes('Tenant Admin')) { console.log('User is not tenant admin, received roles:', userRoles); return true; } return false; }; (async () => { const isMock = /[&?]mock=([^&]+)/.exec(location.search)?.[1]; const shouldLogin = (await getShouldLogin()) && !isMock; const rootEle = document.querySelector('.container'); const widgetEle = document.createElement( 'descope-role-management-widget', ); widgetEle.setAttribute('project-id', DESCOPE_PROJECT_ID); widgetEle.setAttribute('base-url', DESCOPE_BASE_URL); widgetEle.setAttribute('base-static-url', DESCOPE_BASE_STATIC_URL); widgetEle.setAttribute('tenant', DESCOPE_TENANT); widgetEle.setAttribute('widget-id', DESCOPE_WIDGET_ID); widgetEle.setAttribute('debug', 'false'); if (isMock) { widgetEle.setAttribute('mock', 'true'); } if (shouldLogin) { const flowEle = document.createElement('descope-wc'); flowEle.setAttribute('project-id', DESCOPE_PROJECT_ID); flowEle.setAttribute('base-url', DESCOPE_BASE_URL); flowEle.setAttribute('flow-id', 'sign-up-or-in'); flowEle.setAttribute('debug', 'false'); flowEle.addEventListener('success', () => { flowEle.remove(); rootEle.appendChild(widgetEle); }); rootEle.appendChild(flowEle); } else { rootEle.appendChild(widgetEle); } })(); ``` -------------------------------- ### Perform OTP Email Sign-In and Verification Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-js-sdk/README.md Demonstrates the process of signing in a user via OTP email, sending the code, and then verifying it using `sdk.otp.signIn.email` and `sdk.otp.verify.email` methods. This sequence is crucial for passwordless authentication flows. ```js const userIdentifier = 'identifier'; let res = await sdk.otp.signIn.email(userIdentifier); if (!res.ok) { throw Error('Failed to sign in'); } // Get the one time code from email and verify it const codeFromEmail = '1234'; res = await sdk.otp.verify.email(userIdentifier, codeFromEmail); if (!res.ok) { throw Error('Failed to sign in'); } ``` -------------------------------- ### Descope JS SDK Multi-Step Magic Link Authentication Flow Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-js-sdk/examples/magicLink/index.html This JavaScript snippet implements a client-side multi-step authentication process using the Descope SDK. It first prompts the user for a Descope Project ID, then for their email address, and subsequently initiates a magic link sign-up or sign-in. The form dynamically updates its prompt and handles submission, displaying alerts for errors. ```javascript let sdk; let step = 0; let mail; let projId; const fns = [ (projectId) => { projId = projectId; sdk = Descope({ projectId }); }, (email) => { mail = email; const uri = new URL(window.location.href); uri.pathname += 'verify.html'; uri.searchParams.set('projectId', projId); return sdk.magicLink.signUpOrIn.email(email, uri.toString()); }, ]; const texts = ["What's your email?", 'Check your email']; const formEle = document.getElementsByTagName('form')[0]; const h1Ele = document.getElementsByTagName('h1')[0]; const inputEle = document.getElementsByTagName('input')[0]; formEle.onsubmit = async function (e) { e.preventDefault(); const input = new FormData(e.target).get('input'); try { const resp = await fns[step](input); if (resp?.ok === false) alert(JSON.stringify(resp, null, 4)); } catch (e) { alert(e.message); return; } h1Ele.innerText = texts[step]; inputEle.value = ''; step++; if (!texts[step]) formEle.remove(); }; ``` -------------------------------- ### Initialize Descope SDK and Perform OIDC Login Redirect Source: https://github.com/descope/descope-js/blob/main/packages/sdks/web-js-sdk/examples/oidc/index.html This JavaScript snippet captures a project ID from a form input, initializes the Descope SDK with the provided ID, constructs an OIDC configuration including a dynamic redirect URI, and then initiates an OIDC login flow using `sdk.oidc.loginWithRedirect`. It handles the response by alerting on failure and redirecting the user on success, while updating the UI during the process. ```JavaScript const warningEle = document.getElementsByClassName('warning')[0]; const url = new URL(window.location.href); url.pathname += 'exchange'; const formEle = document.getElementsByTagName('form')[0]; const h1Ele = document.getElementsByTagName('h1')[0]; const inputEle = document.getElementsByTagName('input')[0]; formEle.onsubmit = async function (e) { e.preventDefault(); const projectId = new FormData(e.target).get('input'); const sdk = Descope({ projectId }); const url = new URL(location.href); url.pathname += 'finish.html'; url.searchParams.set('projectId', projectId); const redirectUri = url.toString(); const oidcConfig = { // if not specified, clientId is the project ID clientId: projectId, redirectUri, scope: 'openid profile email', }; const res = await sdk.oidc.loginWithRedirect(oidcConfig); if (res?.ok === false) alert(JSON.stringify(res, null, 4)); window.location.href = res.data.url; h1Ele.innerText = 'Redirecting...'; formEle.remove(); }; ``` -------------------------------- ### Example: Defining Private Routes in Next.js Middleware Source: https://github.com/descope/descope-js/blob/main/packages/sdks/nextjs-sdk/README.md This example shows how to use the `privateRoutes` option in the Descope `authMiddleware` configuration. Only routes specified here will require authentication, making all other routes public. Note that if both `publicRoutes` and `privateRoutes` are defined, `privateRoutes` will be ignored. ```typescript const options = { privateRoutes: ['/dashboard', '/profile'] }; ```