/
Contact usSee pricingStart building
Node
​

    About Stytch

    Introduction
    Integration Approaches
      Full-stack overview
      Frontend (pre-built UI)
      Frontend (headless)
      Backend
    Migrations
      Migration overview
      Migrating users statically
      Migrating users dynamically
      Additional migration considerations
      Zero-downtime deployment
      Defining external IDs for users
      Exporting from Stytch
    Custom Domains
      Overview

    Authentication

    DFP Protected Auth
      Overview
      Setting up DFP Protected Auth
      Handling challenges
    Magic Links
    • Email Magic Links

      • Getting started with the API
        Getting started with the SDK
        Replacing your password reset flow
        Building an invite user flow
        Add magic links to an existing auth flow
        Adding PKCE to a Magic Link flow
        Magic Link redirect routing
    • Embeddable Magic Links

      • Getting started with the API
    MFA
      Overview
      Backend integration
      Frontend integration
    Mobile Biometrics
      Overview
    M2M Authentication
      Authenticate an M2M Client
      Rotate client secrets
      Import M2M Clients from Auth0
    OAuth
    • Identity providers

      • Overview
        Provider setup
      Getting started with the API (Google)
      Add Google One Tap via the SDK
      Email address behavior
      Adding PKCE to an OAuth flow
    Connected AppsBeta
      Setting up Connected Apps
      About Remote MCP Servers
    • Resources

      • Integrate with AI agents
        Integrate with MCP servers
        Integrate with CLI Apps
    Passcodes
      Getting started with the API
      Getting started with the SDK
    • Toll fraud

      • What is SMS toll fraud?
        How you can prevent toll fraud
      Unsupported countries
    Passkeys & WebAuthn
    • Passkeys

      • Passkeys overview
        Set up Passkeys with the frontend SDK
    • WebAuthn

      • Getting started with the API
        Getting started with the SDK
    Passwords
      Getting started with the API
      Getting started with the SDK
      Password strength policy
    • Email verification

      • Overview
        Email verification before password creation
        Email verification after password creation
    Sessions
      How to use sessions
      Backend integrations
      Frontend integrations
      Custom claims
      Custom claim templates
      Session tokens vs JWTs
      How to use Stytch JWTs
    TOTP
      Getting started with the API
      Getting started with the SDK
    Web3
      Getting started with the API
      Getting started with the SDK

    Authorization

    Implement RBAC with metadata

    3rd Party Integrations

    Planetscale
    Supabase
    Feathery
    Unit

    Testing

    E2E testing
    Sandbox values
Get support on SlackVisit our developer forum

Contact us

Consumer Authentication

/

Guides

/

Authentication

/

Sessions

/

Frontend integrations

Frontend Sessions guide

In this guide, we'll walk you through how to create and manage Stytch Sessions using our frontend JavaScript SDK. This guide is relevant both to integrations that use our pre-built UI components and integrations that use our headless frontend methods.

Overview

Frontend SDK sessions diagram

When a user successfully authenticates, our frontend JavaScript SDK will automatically store the user's session token and JWT as browser cookies. The user's session token and JWT will then be automatically included in request headers by the browser in all requests to your backend, as long as your frontend and backend share a domain.

Your backend can use the session token or JWT to authenticate the session and determine whether or not it should proceed with the request.

The session token will also be included in all frontend SDK requests to Stytch's servers, so that the SDK can make requests on behalf of the authenticated user.

Background session authentication

The frontend SDK makes background session authentication calls to Stytch servers roughly every three minutes while the user is actively using your application. After each background request, the frontend SDK will replace the old session JWT with a new one, ensuring that the JWT remains unexpired.

The SDK will also update its cached user and session data after its background session authentication calls to reflect any changes in the session data, and will clear the session cookies if the session is no longer valid.

Session cookie configuration

When using the Stytch frontend SDK for session management, you may configure certain values such as the session cookie names and which HTTP paths, domain, and subdomains the cookie should be accessible to.

For additional information, see our Cookies & session management SDK resource.

HttpOnly vs. non-HttpOnly session cookies

By default, session cookies set by the Stytch frontend JavaScript SDK are not marked as HttpOnly. For enhanced security, you can optionally enable the use of HttpOnly cookies for your project.

When HttpOnly cookies are enabled, session handling behavior will remain largely the same, with a few minor differences. Check out our HttpOnly Cookies overview for additional information.

Determining whether there is an active session

You can leverage the frontend SDK's session data to determine whether or not there is an active session for frontend UI and navigation purposes. Choose your frontend framework for additional usage details.

When using our React SDK, you can use the useStytchSession() hook to retrieve the user's session data and listen for changes. The useStytchSession() hook returns two values:

  • session: The user's Stytch Session object, if there is an active session. If there's no active session, the session value will be null.
  • fromCache: true if the SDK hasn't yet completed a session authentication call after loading and is returning cached session data; false if the session authentication call has completed.

For many use cases, like deciding whether or not to render certain frontend content, it's generally fine to rely on the session value. However, for use cases where you'd prefer to wait until the session data finishes updating instead of relying on cached data, you can verify that fromCache is false before checking the session value. See our SWR & caching resource for additional information.

import { useStytchSession } from '@stytch/react';

export const Home = () => {
  const { session } = useStytchSession();

  return session ? <p>Active Session</p> : <p>No Active Session</p>;
};

When using our NextJS SDK, you can use the useStytchSession() hook to retrieve the user's session data and listen for changes. The NextJS useStytchSession() hook returns three values:

  • isInitialized: Whether or not the SDK has finished initializing. Ensure this is true before checking for an active session.
  • session: The user's Stytch Session object, if there is an active session. If there's no active session, the session value will be null.
  • fromCache: true if the SDK hasn't yet completed a session authentication call after loading and is returning cached session data, false if the session authentication call has completed.

For many use cases, like deciding whether or not to render certain frontend content, it's generally fine to rely on the session value as long as isInitialized is true. However, for use cases where you'd prefer to wait until the session data finishes updating instead of relying on cached data, you can verify that fromCache is false before checking the session value. See our SWR & caching resource for additional information.

import { useStytchSession } from '@stytch/nextjs';

export const Home = () => {
  const { session, isInitialized } = useStytchSession();

  if (!isInitialized) {
    return <p>Loading</p>
  }
  return session ? <p>Active Session</p> : <p>No Active Session</p>;
};

When using our Vanilla JavaScript SDK, you can use the stytch.session.getInfo method to retrieve the user's session data. The stytch.session.getInfo method returns two values:

  • session: The user's Stytch Session object, if there is an active session. If there's no active session, the session value will be null.
  • fromCache: true if the SDK hasn't yet completed a session authentication call after loading and is returning cached session data; false if the session authentication call has completed.
import { StytchHeadlessClient } from '@stytch/vanilla-js/headless';

const stytch = new StytchHeadlessClient('PUBLIC_TOKEN');

let { session, fromCache } = stytch.session.getInfo();

if (session && fromCache) {
  // There is a cached session and a session authentication is in progress
} else if (session) {
  // Session authentication has completed and there is an active session
} else {
  // There is no active session
}

You can also use the stytch.session.onChange method to listen for changes in the user's session. The session.onChange method takes in a callback that gets called whenever the session object changes, and it returns an unsubscribe method for you to call when you no longer want to listen for changes.

// Listen for session changes
const unsubscribeSession = stytch.session.onChange((newSession) => {
  session = newSession;
  // Trigger any relevant actions in your application based on the session update
  handleSessionChange();
});

window.addEventListener('beforeunload', () => {
  unsubscribeSession && unsubscribeSession();
});

Extending the lifetime of a session

Once a session has been created, the frontend SDK will keep the session JWT updated by making background session authentication calls, but it will not automatically extend the lifetime of the underlying session. For example, if you set an initial session_duration_minutes of 60 minutes and take no further action, the session will expire after 60 minutes regardless of user activity.

If you would like to extend the lifetime of an active session, you can specify the new desired session length by passing a session_duration_minutes value to the Authenticate session method, which will set the session's lifetime to that many minutes from the present. Note that once a session has expired, it can't be reactivated – in that case, the user will need to log in again and create a new session.

One technique is to set an interval where you extend the session's lifetime so that the session is periodically extended while the user keeps your application open:

const extendSession = () => {
  if (stytch.session.getSync()) {
    // Set the session's expiration to 60 minutes from the present
    stytch.session.authenticate({
      session_duration_minutes: 60,
    });
  }
};
// Extend the session's lifetime every 10 minutes
let interval = setInterval(extendSession, 600000);
window.addEventListener('beforeunload', () => {
  clearInterval(interval);
});

Hydrating a session

If necessary, you can hydrate the frontend SDK with an active session that was created elsewhere. This is useful if your application uses any authentication flows where a session is created or updated on the backend and you'd like the frontend SDK to pick up the most recent session data.

You can do so by providing both the active session_token and the session_jwt to the Update session method, followed by a call to the Authenticate session method.

export const hydrateSession = () => {
  stytch.session.updateSession({
    session_token: 'ACTIVE_SESSION_TOKEN',
    session_jwt: 'ACTIVE_SESSION_JWT',
  });

  stytch.session.authenticate();
};

Note that when HttpOnly cookies are enabled for your Stytch project, the Update session method will only work if there isn't already an existing session token set using an HttpOnly cookie. If you do use the Update session method when HttpOnly cookies are enabled, make sure your Stytch SDK client's cookieOptions are configured to match the domain and cookie names used by Stytch's backend.

Alternatively, you can override the session cookies via response headers from your backend. After doing so, be sure to make a frontend call to the Authenticate session method so that the SDK picks up the new session data.

Revoking a session

The Revoke session method makes a call to Stytch's servers to revoke the active session and clears the session cookies from the user's browser.

export const logout = () => {
  stytch.session.revoke();
};

Overview

Background session authentication

Session cookie configuration

HttpOnly vs. non-HttpOnly session cookies

Determining whether there is an active session

Extending the lifetime of a session

Hydrating a session

Revoking a session