Skip to main content

Step-by-step guide

In this guide, we'll modify an example application to use localstorage instead of cookies. You can find the modified application here

Backend#

On the backend, we need to modify the api-server.js to allow and use our custom cookie. You can find the result here.

1. Allow the custom header on requests#

First, we need to allow the frontend to send the st-cookie header we chose to transfer the tokens. We can do this by adding it to allowedHeaders in the cors config, as seen in line 125.

2. Adding a helper#

Then, we need to add a helper function that will handle copying the Set-Cookie header into our custom header and also add that header to the access-control-expose-headers list so that the frontend can access it on CORS requests. You can find the implementation in the updateHeaders function.

3. Send the tokens using a custom header#

Finally, we need to override most of the functions and APIs of the Session recipe to have them use the header enabled in the first step and to use the helper function defined in the second step to send tokens to the frontend. You can find the modified session recipe config in lines 43-116

Frontend#

On the front end, we need to modify our SuperTokens configuration and patch the global fetch function to add our custom header. You can find the modified App.js here.

1. Adding a helper to store cookies#

First, we need to add a helper function to process the custom header and store the cookies in the proper format. You can find a simple implementation in lines 126-155. Please keep in mind that this isn't an equivalent replacement for cookies; there are many features we didn't implement in the example. Our recommendation is to use cookies if at all possible.

2. Replace global fetch#

important
  • This has to be done before calling SuperTokens.init.

Then, we need to replace the global fetch to make use of the custom header. We need to do this because fetch is used internally by the SuperTokens SDK, and we have no other way of getting access to response headers. You can see how we did it in lines 73-101

3. Clearing cookies on logout#

Finally, we need to add an event handler that will clear the cookies on logout. This is done in an event handler in the configuration of the session recipe, as seen in lines 116-121.

4. An optional step is to add an axios interceptor#

important
  • This step is only applicable if you are using axios

If you are using axios, you need to add an interceptor to add the custom header to requests and handle it in responses. You can see a basic implementation in lines 33-71.