Redirect user to its subdomain in ReactJs

Viewed 41

I am building a react website where I assign a subdomain to the user when they sign up according to the username they enter, let's say their username is john, then the subdomain will be john.mydomain.com.

I would like to know how to redirect a user to its subdomain after they signup. I have access to the user data immediately after signup, such as username.

Sign up code:

export const signup = (formData, history) => async (dispatch) => {
  try {
    // sign up the user
    const { data } = await api.signUp(formData);
    dispatch({ type: "AUTH", data });
    toast.success("Signed Up successfully");
    history.push("/");
  } catch (error) {
    dispatch({ type: "ERROR", data: error?.response?.data });
    toast.error(error?.response?.data?.message);
  }
};

Thank You.

2 Answers

Assuming the subdomain is on the same host you can use History API or fallback on location:

const url = `${window.location.protocol}//${data.username}.${window.location.hostname}`
if (window.history) {
  window.history.pushState(data, '', url) // data included to subdomain
} else {
  const stringifiedData = JSON.stringify(data)
  const encodedData = btoa(stringifiedData) // base64 encode
  window.location.href = `${url}?data=${encodedData}
}

And then on the subdomain:

let data
if (window.history) {
  data = window.history.state // Access the state passed when signing up
  // save to localstorage or something
} else {
  const params = new URLSearchParams(window.location.search)
  const encodedData = params.get('data')
  const decodedData = atob(encodedData) // base64 decode
  const originalData = JSON.parse(decodedData)
  // save to localstorage or something
}

In a new sign up, your server can generate a one time random string, which can be returned to your front end.

Then when you get the random string, you can pass it to your next page

const { data } = await api.signUp(formData);
dispatch({ type: "AUTH", data });
toast.success("Signed Up successfully");
window.location.href = `yourpath?authkey=${data.onetimekey}`

On arrival to your new page, the new page should get the authkey, pass it to backend, to confirm it's authentication status, and send back the user data you need, before you save it to your store in the new domain page.

You need to generate a random string (to be saved to a database of sort), because you should not be passing any private information via the query string.

Related