Auth0 Home Blog Docs

How to save user to local database with SPA and Hosted Login?

spa
react
hosted-login-page
serverside

#1

Hi,

I am using the example code for ReactJS and the Hosted Login flow. It works great. I also have a server that has protected endpoints which assess the access token from the Hosted Login (Authorization: Bearer …). Works like a charm.

The only concern I have is this. The very first time a user signs up, I need to create a record on the server side (api) database before the SPA can really do anything useful. I see two ways of creating that database record:

  1. Use a Rule from Auth0 to make the request to the server side database
  2. Use ReactJS to make the request to the server side database after the Hosted Login redirects back to the app wait just for the response before continuing

My concern about #1 is that I need the Rule to wait until the request to the server side database is complete before continuing and redirecting the user back to the application.

Any thoughts would be much appreciated.

Cheers


#2

If it’s mandatory for your app to work that the record exists in your API’s database, I think it makes more sense to handle this in a rule at login time, rather than after the redirect.

As long as your API offers fast response times, the user shouldn’t experience any significant delay in the login process. Additionally, you need to make sure to handle any connection error gracefully.


#3

Great. Thanks. How can I make sure the Rule “waits” for the response from the request before completing and redirecting back to the app?


#4

The authentication flow will be paused while the rule is executed, and won’t continue unless you invoke the callback, or it times out (in 30 seconds, if I remember correctly).

Here’s some code/pseudo-code of how your rule would look like:

function (user, context, callback) {
  // Here you would have your machine-to-machine
  // authentication code between Auth0 and your API
  
  // Then, you make the request to your API
    request.post({
    url: "https://",
    json: user
  },
  function (err, response, body) {
    if (err) {
      // make sure to gracefully handle error
      // by passing an error to the callback, the authentication fails
      callback(err);
    }
      
    // if there's no error, invoke the callback without error
    // to continue with the auth flow
    callback(null, user, context);
  });

}

#6

Just curious. Why do you prefer making the request in the Rule rather than in the ReactJS app?

One problem I see is that the Rules can’t send requests to localhost (so I can’t develop with a local database)