Hiding an API Token in a theme component

I have a theme component where it sends a request to an external API to fetch some data during a page load. However, the Bearer token I use to fetch this data is naturally loaded in the script that the client has access to. Is there a way to create a plugin or something that will enable me to hide this information?

1 Like

Yes, you should indeed create a plugin, and define a controller method that fetches the data for you.

Then, from the frontend code, call the controller method, which injects the bearer token server side, inaccessible for any third party, and makes the call to the external API.


Rather than creating a new controller to do it (which isn’t clearly what Richard recommended) you can fairly easily add it to an existing serializer, something like

  add_to_serializer(:current_user, :my_stuff) do
    stuff = get_my_stuff_somehow

FIguring out what serializers are available and which one you want is hopefully simple enough (most are pretty easy to guess, but you can find them in app/serializers); searching GitHub - discourse/all-the-plugins for add_to_serializer should provide plenty of examples. And start with GitHub - discourse/discourse-plugin-skeleton: Template for Discourse plugins.

Even if you don’t know Ruby or Rails, the above should give you a pretty good idea what you need to do. If not, you can ask in #marketplace with a budget.

I think it’s a very bad idea to hook an external dependency into a serializer @pfaffman
If the external service goes down or is slow, then your forum will be down as well.


Oh. Well, darn. That does sound true. :person_shrugging:

@attj , this is one of many matters in which I trust what Richard says more than what I say.

I’m afraid you’ll need to do the work to add a route and such, which is quite a few more lines of code ( probably only dozens). I think that Discourse Category Home 🏠 is one that adds a route.


I guess I managed to write a plugin but I need to put it to github in order to include it in my app.yml. Which naturally exposes the token as well. Is there a way to get around this?


Just read the token from a site setting and input it there after installation.


Makes a lot of sense. Thanks!


This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.