Angular & Node.js Quickstart

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

Install Frontend SDK

Install the SDK with the following command:

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

Then, add Descope type definitions to your tsconfig.ts

tsconfig.ts
"compilerOptions": {
  "typeRoots": ["./node_modules/@descope"],
  // ... other options
}

Import Frontend SDK

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

app.module.ts
import { DescopeAuthModule, DescopeAuthService, descopeInterceptor } from '@descope/angular-sdk';

Wrap Application with Descope Angular SDK

Start by importing Descope then add the Angular SDK to your application. You will need your Project ID from Project Settings in the Descope Console.

Note

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

app.module.ts
import { NgModule, APP_INITIALIZER} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { DescopeAuthModule, DescopeAuthService, descopeInterceptor } from '@descope/angular-sdk';
import { AppComponent } from './app.component';
import {
	HttpClientModule,
	provideHttpClient,
	withInterceptors
} from '@angular/common/http';
import { zip } from 'rxjs';
 
export function initializeApp(authService: DescopeAuthService) {
	return () => zip([authService.refreshSession(), authService.refreshUser()]);
}
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    DescopeAuthModule.forRoot({
      projectId: 'YOUR_PROJECT_ID'
    })
  ],
  providers: [
    {
        provide: APP_INITIALIZER,
        useFactory: initializeApp,
        deps: [DescopeAuthService],
        multi: true
      },
      provideHttpClient(withInterceptors([descopeInterceptor]))
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Handle onSuccess and onError Logic

In your Angular template, use the <descope> component to render a specific authentication flow. Customize this component with properties like flowId, (error), (success), and optional attributes for theming, debug mode, and more:

  • theme: "light" or "dark" mode
  • tenant: Tenant ID you can pass in for SSO
  • 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.
  • :errorTransformer: this is a function that receives an error object and returns a string. The returned string will be displayed to the user. errorTransformer is not required. If not provided, the error object will be displayed as is. Learn more about how to use the errorTransformer here.
  • 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" }}
app.component.html
<div style="max-width: 1000px; margin: 0 auto; place-items: center;">
    <descope
        flowId="sign-up-or-in"
        (success)="onSuccess($event)"
        (error)="onError($event)"
    ></descope> 
</div>

Utilize the Angular 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?
  • getSessionToken() - This gets the session token from your browser which you can include in your backend requests
  • logout() - Log the user out of the session
app.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { DescopeAuthService } from '@descope/angular-sdk';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  isAuthenticated: boolean = false;
  token: string = "";
  constructor(
    private router: Router,
    private authService: DescopeAuthService
  ) {}
 
  ngOnInit() {
    this.authService.session$.subscribe((session) => {
      this.isAuthenticated = session.isAuthenticated;
    });
  }
 
  logout() {
    this.authService.descopeSdk.logout();
  }
}

Capturing Events

Implement mechanism to capture and handle authentication successes or errors. Descope provides the ability to customize successful authentication or failed authentication flows.

  • onSuccess - What happens when the user is successfully authenticated?
  • onError - What happens when there's an error on user authentication?

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

app.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { DescopeAuthService } from '@descope/angular-sdk';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  isAuthenticated: boolean = false;
  token: string = "";
  constructor(
    private router: Router,
    private authService: DescopeAuthService
  ) {}
 
  // Handle successful login
  onSuccess(event: CustomEvent) {
    console.log('SUCCESSFULLY LOGGED IN', event.detail);
    this.router.navigate(['/authenticated_page']);
  }
 
  // Handle login error
  onError(event: CustomEvent) {
    console.log('ERROR FROM LOG IN FLOW', event.detail);
  }
 
  ngOnInit() {
    this.authService.session$.subscribe((session) => {
      this.isAuthenticated = session.isAuthenticated;
    });
  }
 
  logout() {
    this.authService.descopeSdk.logout();
  }
}

Install Backend SDK

Install the SDK with the following command:

Terminal
npm i --save @descope/node-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 in the parameters (e.g. {baseUrl : 'https://api.descope.com'}) when you initialize DescopeClient.

index.js
import DescopeClient from '@descope/node-sdk';
 
try {
    const descopeClient = DescopeClient({ projectId: '__ProjectID__' });
} catch (error) {
    console.log("failed to initialize: " + error)
}

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.

index.js
// Fetch session token from HTTP Authorization Header
const sessionToken="xxxx"
 
try {
  const authInfo = await descopeClient.validateSession(sessionToken);
  console.log("Successfully validated user session:");
  console.log(authInfo);
} catch (error) {
  console.log ("Could not validate user session " + error);
}

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