Swift & Node.js Quickstart
This is a quickstart guide to help you integrate Descope with your Swift & Node.js application. Follow the steps below to get started.
Add the DescopeKit package
Next, we need to add the DescopeKit package (our Swift SDK) using the Swift package manager.
- Within XCode, go to File > Add Packages and search for the URL of the git repo: https://github.com/descope/descope-swift.
- Then, configure your desired dependency rule and click "Add Package."
Configure Descope with a custom Project ID
Configure Descope in the scene function of the SceneDelegate.swift. A Descope Project ID is required to initialize the SDK. You can find this ID on the project page in the Descope Console.
Note
Please include the baseUrl parameter in your Descope.setup() only if you're utilizing a custom domain within your Descope project (ex: https://auth.company.com).
import UIKit
import DescopeKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// initialize the Descope SDK before using it
Descope.setup(projectId: "__ProjectID__") { config in
config.baseURL = "<base url>"
}
// show home screen if user is already logged in, otherwise show authentication screen
let initialViewController: UIViewController
if let session = Descope.sessionManager.session, !session.refreshToken.isExpired {
initialViewController = AppInterface.homeScreen
} else {
initialViewController = AppInterface.authScreen
}
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = initialViewController
window?.makeKeyAndVisible()
return true
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
// pass any incoming Universal Links to the current flow in case we're
// using Magic Link authentication in the flows
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL else { return false }
DescopeFlow.current?.resume(with: url)
return true
}
}Add the Flow URL
You'll need to get your flowURL, which is the URL where your authentication flow is hosted on the web (eg. https://example.com/login).
let url = "https://api.descope.com/login/\(Descope.config.projectId)?flow=sign-up-or-in"Call the startFlow function
The 'startFlow' function starts the authentication process with a custom flow url. Optionally, you can customize how flow pages look and behave using pre-defined flow hooks or custom hooks in a DescopeFlowHook extension.
/// Creates a new DescopeFlowViewController, loads the flow into it, and pushes
/// it onto the navigation controller stack
func showFlow() {
// create a new flow object
let url = "https://api.descope.com/login/\(Descope.config.projectId)?flow=sign-up-or-in"
let flow = DescopeFlow(url: url)
flow.hooks = [
// use built-in hook that makes the flow page have a transparent background
.setTransparentBody,
// create hook that injects CSS that sets margins on the body element
.addStyles(selector: "body", rules: [ "margin: 16px" ]),
// apply hooks defined in the DescopeFlowHook extension
.setBodyMargins,
.disableScrolling,
.removeFooter
]
extension DescopeFlowHook {
// injects CSS that sets margins on the body element
static let setBodyMargins = addStyles(selector: "body", rules: [ "margin: 16px" ]),
// disables scrolling in the flow page
static let disableScrolling = setupScrollView({ scrollView in
scrollView.isScrollEnabled = false
})
// runs javascript that removes a footer element when the flow is ready
static let removeFooter = runJavaScript(on: .ready, code: """
const footer = document.querySelector('#footer')
footer?.remove()
""")
}
// create a new DescopeFlowViewController and start loading the flow
let flowViewController = DescopeFlowViewController()
flowViewController.delegate = self
flowViewController.start(flow: flow)
// push the view controller onto the navigation controller
navigationController?.pushViewController(flowViewController, animated: true)
}
/// This action is called when the user taps the Sign In button
@IBAction func didPressSignIn() {
print("Starting sign in with flow")
showFlow()
}Create a UI component to trigger the startFlow function
Here, we implement a Button that when clicked, calls the start flow function we just wrote.
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="5AU-rI-FZH" userLabel="Button">
<rect key="frame" x="32" y="346" width="329" height="48"/>
<constraints>
<constraint firstAttribute="height" relation="greaterThanOrEqual" constant="48" id="VxW-y0-ini"/>
<constraint firstAttribute="height" constant="48" id="vak-nB-FJq"/>
</constraints>
<color key="tintColor" name="AccentColor"/>
<state key="normal" title="Button"/>
<buttonConfiguration key="configuration" style="filled" title="Sign In">
<fontDescription key="titleFontDescription" name="Verdana" family="Verdana" pointSize="17"/>
<color key="baseForegroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</buttonConfiguration>
<connections>
<action selector="didPressSignIn" destination="-1" eventType="touchUpInside" id="Wa5-at-WG8"/>
</connections>
</button>Utilize the Swift SDK Session Management Functions
Descope provides the sessionManager to check if the user is authenticated or get user data such as email, userId, etc. You can use these to customize the user experience:
isAuthenticated: is user authenticated?user: user object that contains all user attributes (email, name, etc.)me: updates the managed session user details and returns itlogout: logs the user out by revoking the active session and clearing it from the session manager/Keychain storage
extension SimpleFlowController: DescopeFlowViewControllerDelegate {
func flowViewControllerDidUpdateState(_ controller: DescopeFlowViewController, to state: DescopeFlowState, from previous: DescopeFlowState) {
print("Flow state changed to \(state) from \(previous)")
}
func flowViewControllerDidBecomeReady(_ controller: DescopeFlowViewController) {
// in this example we don't need to handle the ready event because we're
// just showing the flow immediately without preloading it or anything
}
func flowViewControllerShouldShowURL(_ controller: DescopeFlowViewController, url: URL, external: Bool) -> Bool {
// we return true so that the DescopeFlowViewController does its builtin behavior
// of opening the URL in the user's default browser app
return true
}
func flowViewControllerDidCancel(_ controller: DescopeFlowViewController) {
// in this example the cancel button isn't shown because the DescopeFlowViewController
// isn't at the root of its navigation controller stack, and the user can simply
// tap the built-in Back button to leave the flow screen
}
func flowViewControllerDidFail(_ controller: DescopeFlowViewController, error: DescopeError) {
// errors will usually be .networkError or .flowFailed
print("Authentication failed: \(error)")
showError(error)
}
func flowViewControllerDidFinish(_ controller: DescopeFlowViewController, response: AuthenticationResponse) {
// authentication succeeded so we create a new DescopeSession, give it to the session
// manager, and transition to the user to the home screen
print("Authentication finished")
let session = DescopeSession(from: response)
Descope.sessionManager.manageSession(session)
showHome()
}
}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:
npm i --save @descope/node-sdkyarn add @descope/node-sdkpnpm add @descope/node-sdkbun i @descope/node-sdkImport and Setup Backend SDK
You'll need import and setup all of the packages from the SDK.
If you're using a custom domain with your Descope project, make sure to include baseUrl in the parameters (e.g. {baseUrl : 'https://api.descope.com'}) when you initialize DescopeClient.
import DescopeClient from '@descope/node-sdk';
try {
const descopeClient = DescopeClient({ projectId: '__ProjectID__' });
} catch (error) {
console.log("failed to initialize: " + error)
}Implement Session Validation
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.
You will need to then fetch the session token from the Authorization header of each request, and use the SDK to validate the token.
Note
You can optionally validate the aud claim by passing an audience parameter. This ensures the token was issued for your specific application and prevents token reuse across different applications. The audience parameter accepts either a string or an array of strings.
// Fetch session token from HTTP Authorization Header
const sessionToken = "xxxx";
try {
// Basic validation without audience checking
const authInfo = await descopeClient.validateSession(sessionToken);
// Or validate with a single audience (string)
const authInfoWithAudience = await descopeClient.validateSession(sessionToken, {
audience: '__ProjectID__'
});
// Or validate with multiple audiences (array)
const authInfoWithMultipleAudiences = await descopeClient.validateSession(sessionToken, {
audience: ['__ProjectID__', 'my-custom-audience']
});
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.
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.