Comment on page

Redirect logged in users from the root domain to the Bubble app

How to redirect logged in Bubble users from the marketing page in the root domain to the Bubble app in a subdomain



Sometimes the Bubble app is in a subdomain and the main marketing page, not built with Bubble, is in the root domain.
There are links in the main page that navigate the user to the Bubble app login/sign up page.
And a usual flow is that if a user access the marketing page were logged in in the Bubble app, that user is redirected to the Bubble app.
To achieve this, we need to read a cookie with the user session information from the root domain. And we are going to need to create that cookie because the cookie Bubble uses to store the session is set on the subdomain so it cannot be read from the main domain.

Target audience

Apps that are hosted in a subdomain.

Goals of the article

In this article we are going to:
  • explain how to create a cookie from the Bubble app that is readable from the main domain.
  • explain how to remove the cookie
  • explain how to read the cookie from the main domain and redirect the user to the Bubble app.
The cookie has to store 3 pieces of info:
  1. 1.
    That the user is logged in.
  2. 2.
    The root domain.
  3. 3.
    The expiration date.
You are going to have to sync this cookie with the user's session status. This means creating the cookie when the user logs in/signs up and remove it when he/she logs out. Options:
  • If you make the user "stay logged in" you can set an expiration date far in the future, like the year 3,000.
  • If you don't make the user "stay logged in" you have to set an expiration date of 24 hours to be in sync with the Bubble session.
  • If you want the cookie to expire at the end of the session, just don't set an expiration date (warning: this will make it not to be in sync with the Bubble session).
Use a Run action to create the cookie:
Setting a cookie to expire in 24 hours
The code:
// time to expire
hoursToExpire = 24;
var date = new Date();
// set cookie
document.cookie = "loggedin=true;; expires=" + date.toGMTString();
When the user logs out, you'll want to remove the cookie. For this you'll use another Run javascript to set the expiration date on the past:
The code:
// remove cookie
document.cookie = "loggedin=;; expires=Thu, 01 Jan 1970 00:00:00 GMT";
In the root domain you have to add this code between the <head> and </heads> tags of the page html. Depending on the service you are using to host the page, this will vary.
As an example, webflow lets you add custom code to all the pages in Site settings -> Advance if your app is in a paid plan.
The code:
<script type="text/javascript">
function getCookie(cookieName) {
  let cookie = {};
  document.cookie.split(';').forEach(function(el) {
    let [key,value] = el.split('=');
    cookie[key.trim()] = value;
  return cookie[cookieName];
var loggedin = getCookie("loggedin");
if(loggedin == "true"){
    //go to the app