@descope/web-js-sdk
Descope JavaScript web SDK
Usage
Install the package
npm install @descope/web-js-sdk
Use it
import descopeSdk from '@descope/web-js-sdk';
const myProjectId = 'xxx';
const sdk = descopeSdk({
projectId: myProjectId,
persistTokens: true,
*/
sessionTokenViaCookie: false,
autoRefresh: true,
storeLastAuthenticatedUser: false,
keepLastAuthenticatedUserAfterLogout: true,
refreshCookieName: "cookie-1"
getExternalToken: async () => {
return 'my-external-token';
},
});
sdk.onSessionTokenChange((newSession, oldSession) => {
});
sdk.onIsAuthenticatedChange((isAuthenticated) => {
});
sdk.onUserChange((newUser, oldUser) => {
});
sdk.refresh();
const userIdentifier = 'identifier';
let res = await sdk.otp.signIn.email(userIdentifier);
if (!res.ok) {
throw Error('Failed to sign in');
}
const codeFromEmail = '1234';
res = await sdk.otp.verify.email(userIdentifier, codeFromEmail);
if (!res.ok) {
throw Error('Failed to sign in');
}
const sessionToken = sdk.getSessionToken();
Usage with OIDC
Descope also supports OIDC login. To enable OIDC login, pass oidcConfig
attribute to the SDK initialization. The oidcConfig
attribute is either a boolean or a configuration object. If you pass oidcConfig: true
, the SDK will use the Descope OIDC default application
const sdk = descopeSdk({
projectId: 'xxx',
oidcConfig: true,
});
const sdk = descopeSdk({
projectId: 'xxx',
oidcConfig: {
applicationId: 'my-application-id',
redirectUri: 'https://my-app.com/redirect',
scope: 'openid profile email',
},
});
Start OIDC login
Login with OIDC is done by calling the loginWithRedirect
method. This method will redirect the user to the Descope OIDC login page. After the user logs in, they will be redirected back to the application to finish the login process.
await sdk.oidc.loginWithRedirect({
redirect_uri: window.location.origin,
});
Finish OIDC login
After the user is redirected back to the application with oidc code and state query parameters, you need to call the oidc.finishLogin
or oidc.finishLoginIfNeed
methods to finish the login process
Using finishLoginIfNeed
(recommended):
await sdk.oidc.finishLoginIfNeed();
Using finishLogin
:
await sdk.oidc.finishLogin();
Manage OIDC session
The SDK will automatically manage the OIDC session for you, according to persistTokens
and autoRefresh
options. The SDK will automatically refresh the OIDC session when it expires, and will store the session token in the browser storage or cookies, according to the persistTokens
option.
Run Example
To run the example:
- Install dependencies
pnpm i
- Run the sample
pnpm run start
The browser open a tab with directory tree of available examples. Click on the desire directory and follow the instruction.
NOTE: This package is a part of a monorepo. so if you make changes in a dependency, you will have to rerun npm run start
(this is a temporary solution until we improve the process to fit to monorepo).