Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use localStorage across subdomains

People also ask

Can local storage be shared between subdomains?

Way to Solution That's because localstorage doesn't support sharing the storage across subdomains or even domain. Thus, if you have something stored at a.example.com it won't be accessible from example.com or b.example.com.

Can localStorage be shared between domains?

Solution: Use an iframe to save the data in localStorage, and then the other domains ask the iframe for what we already saved.

Why we should not use localStorage?

Why Local Storage is Insecure and You Shouldn't Use it to Store Sensitive Data. Here's the deal: most of the bad things about local storage aren't all that important. You can still get away with using it but you'll just have a slightly slower app and minor developer annoyance.

How do I share data between different domains?

It is possible to do "cross-domain localStorage", but it would typically use an iframe with window. postMessage() to share data between domains.


This is how I use it across domains...

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

I hope it helps :)


If you're using the iframe and postMessage solution just for this particular problem, I think it might be less work (both code-wise and computation-wise) to just store the data in a subdomain-less cookie and, if it's not already in localStorage on load, grab it from the cookie.

Pros:

  • Doesn't need the extra iframe and postMessage set up.

Cons:

  • Will make the data available across all subdomains (not just www) so if you don't trust all the subdomains it may not work for you.
  • Will send the data to the server on each request. Not great, but depending on your scenario, maybe still less work than the iframe/postMessage solution.
  • If you're doing this, why not just use the cookies directly? Depends on your context.
  • 4K max cookie size, total across all cookies for the domain (Thanks to Blake for pointing this out in comments)

I agree with other commenters though, this seems like it should be a specifiable option for localStorage so work-arounds aren't required.


I suggest making site.com redirect to www.site.com for both consistency and for avoiding issues like this.

Also, consider using a cross-browser solution like PersistJS that can use each browser native storage.


Set to cookie in the main domain -

document.cookie = "key=value;domain=.mydomain.com"

and then take the data from any main domain or sub domain and set it on the localStorage