@descope/nextjs-sdk 0.16.34 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -74,6 +74,8 @@ const Page = () => {
74
74
  };
75
75
  ```
76
76
 
77
+ This minimal page always sends users to `/` and shows the flow even when the session can still be renewed. For a production sign-in page that returns users to the page they asked for, see [What the app is expected to do](#what-the-app-is-expected-to-do).
78
+
77
79
  Refer to the [Descope React SDK Section](../react-sdk/README.md) for a list of available props.
78
80
 
79
81
  > **Breaking change (v-next):** if you render custom screens via `onScreenUpdate`, the
@@ -153,6 +155,24 @@ const App = () => {
153
155
  >
154
156
  > `isAuthenticated` is derived from the session's expiration, which the SDK receives in every token-storage mode. Read `sessionToken` only when you actually need the raw JWT (for example to attach it to an API request), and use `claims` to read claims out of the session. On the server side, use [`session()`](#read-session-information-in-server-side) instead.
155
157
 
158
+ #### SSO Single Logout
159
+
160
+ When the user signed in through a SAML SSO configuration that has single logout turned on, pass `ssoLogout: true` to `sdk.logout` (or `sdk.logoutAll`) to also log the user out of the identity provider. The Descope session ends either way. If there is a logout to do at the identity provider, the response has `ssoLogoutUrl`, and the app sends the browser to it. The identity provider then sends the browser back to `redirectUrl`, which must be in the project's approved domains (when empty, the SSO configuration's redirect URL is used).
161
+
162
+ ```js
163
+ const sdk = useDescope();
164
+
165
+ const handleLogout = useCallback(async () => {
166
+ const res = await sdk.logout(undefined, {
167
+ ssoLogout: true,
168
+ redirectUrl: 'https://app.example.com/signed-out'
169
+ });
170
+ if (res.data?.ssoLogoutUrl) {
171
+ window.location.href = res.data.ssoLogoutUrl;
172
+ }
173
+ }, [sdk]);
174
+ ```
175
+
156
176
  #### Activity-Based Session Refresh
157
177
 
158
178
  By default, the SDK fires a periodic heartbeat (refresh call) whenever the tab is active. You can opt in to fine-grained control by passing `autoRefresh={{ customActivityTracking: true }}` to `AuthProvider`. With this mode enabled, the SDK only refreshes when `sdk.markUserActive()` has been called since the last refresh — useful for enforcing server-side inactivity timeouts.
@@ -310,12 +330,199 @@ const options = {
310
330
 
311
331
  ###### What the app is expected to do
312
332
 
313
- A user with an expired session token and a still valid refresh token is redirected to the sign-in route.
314
- On the client, `AuthProvider` refreshes the session token from the refresh token on its own (`autoRefresh` is on by default), so the user becomes authenticated again without re-authenticating.
333
+ A user with an expired session token and a still valid refresh token is redirected to the sign-in route. They don't need to sign in again: the browser SDK can renew the session token from the refresh token. Your app has to let it, then send the user back. That takes these pieces:
334
+
335
+ 1. **Keep the requested page.** The redirect replaces the original pathname and only carries over its query parameters, so add the path as `next` yourself. Apply `skipRefreshTokenValidation` to page loads only, so a user with a valid refresh token is not redirected in the middle of a server action or API call. Those handlers check `session()` themselves. If the app sets `basePath`, or serves GET route handlers outside `/api`, adjust the sign-in URL and the `isPageLoad` check.
336
+
337
+ ```ts
338
+ // src/proxy.ts (Next.js 16+) or src/middleware.ts (Next.js 13-15)
339
+ import { NextResponse, type NextRequest } from 'next/server';
340
+ import { authMiddleware } from '@descope/nextjs-sdk/server';
341
+
342
+ // Added to the defaults ('/sign-in', '/sign-up'). All other routes are private.
343
+ const publicRoutes = ['/', '/sign-in', '/api/public/*'];
344
+
345
+ const pageAuth = authMiddleware({
346
+ // projectId defaults to process.env.NEXT_PUBLIC_DESCOPE_PROJECT_ID
347
+ redirectUrl: '/sign-in',
348
+ publicRoutes,
349
+ skipRefreshTokenValidation: true
350
+ });
351
+
352
+ const requestAuth = authMiddleware({ redirectUrl: '/sign-in', publicRoutes });
353
+
354
+ export default async function proxy(req: NextRequest) {
355
+ const isPageLoad =
356
+ req.method === 'GET' &&
357
+ !req.headers.has('next-action') &&
358
+ !req.nextUrl.pathname.startsWith('/api');
359
+ if (!isPageLoad) return requestAuth(req);
360
+
361
+ const res = await pageAuth(req);
362
+ if (res.headers.get('location')) {
363
+ // Redirected to sign-in: remember the page the user asked for.
364
+ const signIn = new URL('/sign-in', req.url);
365
+ signIn.searchParams.set('next', req.nextUrl.pathname + req.nextUrl.search);
366
+ return NextResponse.redirect(signIn);
367
+ }
368
+ return res;
369
+ }
370
+
371
+ export const config = {
372
+ matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)']
373
+ };
374
+ ```
375
+
376
+ 2. **Wait for renewal on the sign-in page.** `<Descope redirectAfterSuccess="/" />` is not enough: it shows the flow to a user whose refresh token is still valid and drops the page they asked for. Wait for `useSession()` to finish loading and return an authenticated user to `next`. Validate `next` by parsing it as a URL: browsers strip tabs and newlines, so string checks such as `startsWith('/')` let `/%09/evil.com` through.
377
+
378
+ ```tsx
379
+ // src/app/sign-in/page.tsx
380
+ 'use client';
381
+
382
+ import { Suspense, useEffect, useRef } from 'react';
383
+ import { useRouter, useSearchParams } from 'next/navigation';
384
+ import { Descope } from '@descope/nextjs-sdk';
385
+ import { useSession } from '@descope/nextjs-sdk/client';
386
+ import { ensureFreshSession } from '@/lib/ensureFreshSession';
387
+
388
+ // Only allow paths inside this app, so ?next= can't send users to another site.
389
+ // Parse instead of string checks: browsers strip tabs and newlines from URLs, so
390
+ // "/\t/evil.com" passes a startsWith('/') check and still leaves the site.
391
+ function safeNext(value: string | null): string {
392
+ if (!value) return '/';
393
+ try {
394
+ const base = 'http://app.invalid'; // placeholder origin, only used for parsing
395
+ const url = new URL(value, base);
396
+ if (
397
+ url.origin !== base ||
398
+ url.pathname.startsWith('//') ||
399
+ url.pathname.startsWith('/sign-in')
400
+ ) {
401
+ return '/';
402
+ }
403
+ return url.pathname + url.search + url.hash;
404
+ } catch {
405
+ return '/';
406
+ }
407
+ }
408
+
409
+ const LAST_RETURN_KEY = 'sign-in-last-return';
410
+
411
+ function SignIn() {
412
+ const router = useRouter();
413
+ const params = useSearchParams();
414
+ const next = safeNext(params.get('next'));
415
+ const renewFailed = params.has('renewFailed');
416
+ const { isAuthenticated, isSessionLoading } = useSession();
417
+
418
+ const returning = useRef(false);
419
+
420
+ useEffect(() => {
421
+ // Run once per mount: React Strict Mode runs effects twice in development.
422
+ if (!isAuthenticated || renewFailed || returning.current) return;
423
+ returning.current = true;
424
+ (async () => {
425
+ // Sent back here seconds after returning the user: the server is rejecting the
426
+ // renewed session. Show the login flow instead of looping. Measure from page
427
+ // load, so a slow refresh doesn't hide the loop.
428
+ const startedAt = Date.now();
429
+ const last = Number(sessionStorage.getItem(LAST_RETURN_KEY) ?? 0);
430
+ // The SDK can report a session whose token is still being renewed.
431
+ await ensureFreshSession();
432
+ if (startedAt - last < 10_000) {
433
+ router.replace(
434
+ `/sign-in?renewFailed=1&next=${encodeURIComponent(next)}`
435
+ );
436
+ return;
437
+ }
438
+ sessionStorage.setItem(LAST_RETURN_KEY, String(Date.now()));
439
+ router.replace(next);
440
+ })();
441
+ }, [isAuthenticated, renewFailed, next, router]);
442
+
443
+ // Let the SDK renew the session from the refresh token before showing the login flow.
444
+ if (!renewFailed && (isSessionLoading || isAuthenticated)) {
445
+ return <p>Checking your session...</p>;
446
+ }
447
+
448
+ return (
449
+ <Descope
450
+ flowId="sign-up-or-in"
451
+ onSuccess={() => {
452
+ sessionStorage.removeItem(LAST_RETURN_KEY);
453
+ router.replace(next);
454
+ }}
455
+ onError={(e) => console.error('Auth failed:', e.detail)}
456
+ />
457
+ );
458
+ }
459
+
460
+ export default function SignInPage() {
461
+ return (
462
+ <Suspense>
463
+ <SignIn />
464
+ </Suspense>
465
+ );
466
+ }
467
+ ```
468
+
469
+ 3. **Refresh on every page.** `AuthProvider` alone does not refresh the session: the SDK starts once a component calls `useSession()`, and then also renews an expired token when the user returns to the tab. Render this once inside `AuthProvider` in the root layout.
315
470
 
316
- Your sign-in page is expected to send an already authenticated user away, otherwise they will sit on it.
317
- Rendering `<Descope />` with `redirectAfterSuccess` covers this, as does checking `useSession()` and routing away yourself.
318
- The redirect replaces the original pathname and only carries over its query parameters, so if you want to return the user to the page they came from, capture it yourself before redirecting.
471
+ ```tsx
472
+ // src/app/components/SessionKeeper.tsx
473
+ 'use client';
474
+
475
+ import { useSession } from '@descope/nextjs-sdk/client';
476
+
477
+ export function SessionKeeper() {
478
+ useSession(); // starts the SDK's session refresh on every page
479
+ return null;
480
+ }
481
+ ```
482
+
483
+ 4. **Wait for renewal before server actions.** Right after the user returns to a background tab, the renewal is still in flight. From a client component, wait for it before calling a server action. The action still checks `session()` itself.
484
+
485
+ ```ts
486
+ // src/lib/ensureFreshSession.ts
487
+ 'use client';
488
+
489
+ import {
490
+ getSessionToken,
491
+ isSessionTokenExpired,
492
+ refresh
493
+ } from '@descope/nextjs-sdk/client';
494
+
495
+ export async function ensureFreshSession() {
496
+ const token = getSessionToken();
497
+ // getSessionToken() returns '' when Descope manages the token as an HttpOnly
498
+ // cookie. Then this does nothing and the SDK's background renewal applies.
499
+ if (token && isSessionTokenExpired(token)) {
500
+ await refresh().catch(() => {});
501
+ }
502
+ }
503
+ ```
504
+
505
+ ```tsx
506
+ // src/app/projects/[id]/settings/SaveForm.tsx
507
+ 'use client';
508
+
509
+ import { ensureFreshSession } from '@/lib/ensureFreshSession';
510
+ import { saveDescription } from './actions';
511
+
512
+ export function SaveForm({ id }: { id: string }) {
513
+ return (
514
+ <form
515
+ action={async (formData) => {
516
+ await ensureFreshSession();
517
+ await saveDescription(id, formData);
518
+ }}
519
+ >
520
+ <input name="description" />
521
+ <button type="submit">Save</button>
522
+ </form>
523
+ );
524
+ }
525
+ ```
319
526
 
320
527
  ##### Read session information in server side
321
528
 
@@ -3,7 +3,7 @@
3
3
  const DESCOPE_SESSION_HEADER = 'x-descope-session';
4
4
  const baseHeaders = {
5
5
  'x-descope-sdk-name': 'nextjs',
6
- 'x-descope-sdk-version': "0.16.34"
6
+ 'x-descope-sdk-version': "0.17.1"
7
7
  };
8
8
  const DEFAULT_PUBLIC_ROUTES = {
9
9
  signIn: process.env.SIGN_IN_ROUTE || '/sign-in',
@@ -3,7 +3,7 @@
3
3
  // eslint-disable-next-line import/prefer-default-export
4
4
  const baseHeaders = {
5
5
  'x-descope-sdk-name': 'nextjs',
6
- 'x-descope-sdk-version': "0.16.34"
6
+ 'x-descope-sdk-version': "0.17.1"
7
7
  };
8
8
 
9
9
  exports.baseHeaders = baseHeaders;
@@ -1,7 +1,7 @@
1
1
  const DESCOPE_SESSION_HEADER = 'x-descope-session';
2
2
  const baseHeaders = {
3
3
  'x-descope-sdk-name': 'nextjs',
4
- 'x-descope-sdk-version': "0.16.34"
4
+ 'x-descope-sdk-version': "0.17.1"
5
5
  };
6
6
  const DEFAULT_PUBLIC_ROUTES = {
7
7
  signIn: process.env.SIGN_IN_ROUTE || '/sign-in',
@@ -1,7 +1,7 @@
1
1
  // eslint-disable-next-line import/prefer-default-export
2
2
  const baseHeaders = {
3
3
  'x-descope-sdk-name': 'nextjs',
4
- 'x-descope-sdk-version': "0.16.34"
4
+ 'x-descope-sdk-version': "0.17.1"
5
5
  };
6
6
 
7
7
  export { baseHeaders };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@descope/nextjs-sdk",
3
- "version": "0.16.34",
3
+ "version": "0.17.1",
4
4
  "description": "Descope NextJS SDK",
5
5
  "author": "Descope Team <info@descope.com>",
6
6
  "homepage": "https://github.com/descope/descope-js",
@@ -64,9 +64,9 @@
64
64
  },
65
65
  "dependencies": {
66
66
  "@descope/node-sdk": "2.8.0",
67
- "@descope/react-sdk": "3.5.7",
68
- "@descope/core-js-sdk": "2.78.0",
69
- "@descope/web-component": "4.7.5"
67
+ "@descope/react-sdk": "3.6.1",
68
+ "@descope/core-js-sdk": "2.79.0",
69
+ "@descope/web-component": "4.8.1"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@babel/core": "7.29.6",