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.:
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.
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.
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
On the backend, we need to do two things:
- Load tokens from a custom header instead of the
- Use a custom header to communicate changes to the tokens instead of setting them as cookies
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.