Skip to main content

Localstorage instead of cookies

Using the features in the "advanced customizations" section, we can customize the SDK to use localstorage instead of cookies for session management. This may be necessary if you want your API and website base domains to be (e.g.: api.example.com and xyz.com), because in this case Safari blocks our cookies. This is not the recommended solution, for more details please check out this issue.

You can find the complete example on GitHub.

How the modification works#

The basic idea behind it is that we can use a custom header to transfer tokens. This way, the frontend can access and store them in localstorage or wherever desired and use them to authenticate requests.

caution

Storing tokens in localstorage comes with a few drawbacks:

  • Increased damage potential of XSS attacks because they can now access the longer-term refresh token
  • Expired tokens are not automatically removed
  • No session info during server-side rendering
  • You can't share sessions across subdomains

For a detailed comparison, please see our blog

Backend#

On the backend, we need to do two things:

  • Load tokens from a custom header instead of the Cookie header
  • Use a custom header to communicate changes to the tokens instead of setting them as cookies

Frontend#

On the frontend we need to do two things:

  • When making a request to the API, we need to add a custom header that contains the tokens we would typically send as cookies
  • After getting a response from the API, we need to inspect the headers and store the contents of a custom header

We can achieve these by replacing the global fetch function with a "patched" version. This must be done before initializing SuperTokens (calling SuperTokens.init) as the SDK uses the fetch function internally.

If you use axios (or a similar library) to make requests, you also need to add an interceptor that will do the same.

Which frontend SDK do you use?
supertokens-web-js / mobile
supertokens-auth-react