Skip to main content

Switch between cookie and header-based sessions

Overview

SuperTokens supports 2 methods of authorizing requests. The following guide shows you how to switch between them.

  • The default in the web SDKs
  • Uses HttpOnly cookies by default to prevent token theft via XSS

Header based

  • The default in the mobile SDKs
  • Uses the Authorization header with a Bearer auth-scheme
  • This can make it easier to work with API gateways and third-party services
  • Preferable in mobile environments, since they can have buggy and/or unreliable cookie implementations

When creating or authorising sessions, the SDK has to choose to send the tokens to the frontend by cookies or custom headers. The backend controls this choice, but it follows a preference set in the frontend configuration.

Before you start

caution

We recommend cookie-based sessions in browsers because header-based sessions require saving the access and refresh tokens in storage vulnerable to XSS attacks.

Steps

1. Update the frontend configuration

You can provide a tokenTransferMethod property in the configuration of the Session recipe to set the preferred token transfer method. The backend receives this method with every request in the st-auth-mode header. By default, the backend follows this preference.

What type of UI are you using?

import SuperTokens from "supertokens-auth-react";
import Session from "supertokens-auth-react/recipe/session";

SuperTokens.init({
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "..."
},
recipeList: [
Session.init({
tokenTransferMethod: "header" // or "cookie"
})
]
});

2. Update the backend configuration Optional

This step is optional. You can force the backend to use a specific token transfer method regardless of the frontend configuration.

caution

You should not set this on the backend if you have more than one client using different modes (for example if you have a website that uses cookie based, and a mobile app that uses header based sessions).

import SuperTokens from "supertokens-node";
import Session from "supertokens-node/recipe/session";

SuperTokens.init({
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "..."
},
recipeList: [
Session.init({
getTokenTransferMethod: () => "header",
})
]
});
note

By default, session verification allows both cookie and authorization bearer tokens. When creating a new session, it follows the preference of the frontend indicated by the st-auth-mode request header (set by the frontend SDK).