Use Localstorage Across Subdomains

Use localStorage across subdomains

This is how I use it across domains...

  • Use an iframe from your parent domain - say parent.example
  • Then on each child.example domain, just do a postMessage to your parent.example iframe
  • All you need to do is setup a protocol of how to interpret your postMessage messages to talk to the parent.example iframe.

How to share localstorage among different subdomains?

Since the domains are not the same, transferring information from the local storage of one of them to another isn't possible directly, but since the sites are on HTTPS, it should be safe and easy enough to send the authentication token as search parameters. For example, when redirecting, instead of redirecting to https://world.website.com, instead take the current authentication token for https://hello.website.com and append it, then redirect:

const url = 'https://world.website.com?token=' + authToken;
window.location.href = url;

(if the authentication token may have special characters in it, you may need to escape them first)

Then, on the other domain, check to see if there's a token in the search parameters, and if so, extract it and save it to localStorage:

const paramsMatch = window.location.href.match(/\?.+/);
if (paramsMatch) {
const params = new URLSearchParams(paramsMatch[0]);
const authToken = params.get('token');
if (authToken) {
localStorage.authToken = authToken;
}
}

Because the domains are on HTTPS, putting the token in the URL is mostly safe - eavesdroppers will not be able to see it. But if your server that handles the requests saves logs, you may find it undesirable for the server to have its logs include authentication tokens as a result of this approach.

Another way would be for:

  • Webapp 1 to make a POST request to Webapp 2 with the token in the payload (where Webapp 2 has the appropriate CORS settings)
  • Webapp 2 generates a new unique URL (that expires after, say, 30 minutes), associates the token with that URL, and responds to the client on Webapp 1 with the URL
  • The client receives the response from Webapp 2 and then navigates to the unique URL on Webapp 2 that it was just given
  • Webapp 2, when handling the request, sees that the unique URL was associated with a token, and goes through the process of fully associating that token with the request session

Do subdomains share local storage?

localStorage is based on a Document's origin. For example, the origin of this page is:

self.origin; // "https://stackoverflow.com"

So, no, localStorage will not be shared across subdomains. If you did want to share localStorage across sub-domains, there is a solution here on SO for that :)

Accessing localStorage from subdomain

This is impossible, because localStorage is a Web-API-method of the/a browser, not the/a server.



Related Topics



Leave a reply



Submit