Connecting API Data: Authentication

The two videos on connecting API data were very helpful, but did not go into authentication concerns.

In my example, I want to store the API base URL and authentication credentials in Builder. Is the best way to do this with a data model?

Authentication needs to run to get a token, which is to be passed with each request, in the http header. What is the best place to locate the call to get an auth header? Also, the token expires after 15 mins non usage, so, there needs to be a mechanism to refresh or retrieve a new token.

I want for all of this to happen in the server side, to protect the auth credentials as well as the token.

Any advice is appreciated!

Hi @rjakes You can give it a try using our Builder.io HTML API - Builder.io

Feel free to reach out if this doesn’t help!

@garima , thank you for your reply!
I’m not yet following how this helps. I’m talking about connecting to an external, third party, API. Please let me know if I’m missing something obvious.

Hi @rjakes, Previously I suggest HTML API as it pre-renders the content server-side and thought of it in a different way, thanks for further clarification.

  1. You can manage authentication & authorization in builder using Advanced Data Fetching techniques.

  2. You can certainly add an Authorization Header to API calls with some custom javascript written. You can find stepwise instructions again at Creating Dynamic URLs with Advanced Data Fetching.

Hope this was able to help, but please feel free to reach out if you face issues while achieving this or email us at support@builder.io!

@rjakes I have the same problem where I would like to use an external API that requires requests made on a server to populate data. Here’s what I’ve tried so far:

  • Create an eCommerce plugin–Looks like these requests always have to go through the browser so this won’t work.
  • Use getAsyncProps to fetch data–This is very promising but it has this annoying issue where the data isn’t accessible in preview because the preview is client-side only.

I feel like there should be a way that we can use what works in production in the preview. The alternative is to pump all our data into data models, which is really not maintainable nor elegant.

1 Like

Can you describe how you handle auth and token expiration/refresh?

@vrio_dave

Where does the authentication to the API live? Are the keys and tokens back in Builder, or are they embedded in the browser?

After much time spent researching and trying various things, answering my own question:

Use middleware.

There are numerous complications with with trying to connect to an authenticated API with Builder, directly. In addition, if there are going to be interactions directly from the browser, you’ll need the middleware anyway. We threw together some code that runs under web app server. Running the middleware under the same name as the website has certain advantages as well.