hurricanenate

hurricanenate

How to integrate Phoenix with a React SPA

My company is taking its first steps in integrating an existing React SPA into a brand-new Phoenix app. We’ve set up auth using phoenix.gen.auth, and are looking at the first case where we need Phoenix-generated data in our UI layer: adding a logout link to our header.

This is how the link is generated in _user_menu.html.heex:

<li><%= link "Log out", to: Routes.user_session_path(@conn, :delete), method: :delete %></li>

What’s the best way to recreate this in our React app?

The first approach I came up with was to add a template that puts any data we might need into a <script></script> tag and attaches it to the window object so that our React components could grab it. This is how I implemented it:

root.html.heex:

<head>
  ...
  <%= render "_script_data.html", assigns %>
  ...
</head>

_script_data.html.heex:

<script type="text/javascript">
  window.dashboardAppData = {
    currentUser: {
      <%= if @current_user do %>
        email: '<%= @current_user.email %>',
      <% end %>
    },
    csrfToken: document.querySelector("meta[name='csrf-token']").getAttribute("content"),
    routes: {
      userSessionDelete: '<%= Routes.user_session_path(@conn, :delete) %>',
      ...
    }
  }
</script>

My React component, HeaderToolbar.js:

function HeaderToolbar() {
  const appData = window?.dashboardAppData;

  return (
    {appData && (
      <a
        href={appData.routes.userSessionDelete}
        data-to={appData.routes.userSessionDelete}
        data-method="delete"
        data-csrf={appData.csrfToken}
      >
        Log Out
      </a>
    }
  )
}

This approach seems workable, but far from ideal: I don’t love the step of creating a giant object of data and making decisions each time about naming conventions. I also lose the utility of the <%= link ... %> tag, as I’m forced to recreate what a Phoenix link looks like, mirroring the necessary data attributes first by rendering it normally in a template and then recreating it in my React component.

Does anyone have any suggestions for better ways to approach this integration? Whatever choices we make at this point will determine the pattern for how we do quite a bit of other work and I’d like to find the best option possible.

First 10 of 10 Posts Switch mode

tomkonidas

tomkonidas

There is a chapter at the end of Real-Time Phoenix that goes into integrating with other front ends using channels.

There is specifically a section Exploring Front-End Technologies → Single-Page Apps with React

hurricanenate

hurricanenate OP

Thanks a lot for that tip—I’ve just purchased the book and will check it out ASAP.

hurricanenate

hurricanenate OP

One question: it looks like the book deals with integrating with Phoenix channels, which I understand to be open connections that let you receive data as it is updated or changed directly from the server. Does it deal at all with the question of how to integrate the rendering layer, as in my example with the log out button in the OP? Right now I’m most curious about how to approach the rendering layer of views in React components.

kokolegorille

kokolegorille

There is a tool to help rendering React with Elixir.

I am curious about the previous backend, and how it was working before.

tomkonidas

tomkonidas

I would think so. Looking fast at the book on page 280.

Well-factored components can be difficult to grasp without a concrete example to show the way. We’ll be working on a Phoenix application with a single-page React front end. You’ll see examples of container components, presentation components, and how to wire them together with contexts and React Router. There will be a bit of React-specific patterns that you may not be used to, but don’t worry too much if you’re not familiar with React.

I assume the presentation components are the ones you are interested in. It looks like he is using normal React Router. You would probably still need to do some sort of JSON API/GraphQL/Channels call in the route component I would guess. This also would depend if you are only using React, or just sprinkling it in a Phoenix app. The way he shows in the book I believe would be using React as the only front end and then using Channels to talk to the Phoenix backend.

joaoevangelista

joaoevangelista

hi!
idk if I understood correctly, but you want to pass to the react components the result of Routes.user_session_path(@conn, :delete) so it can know what url to call to log out?

Is the react app being embedded in a phoenix template? If so, you could assign the routes to an object at the window, as you did, or maybe as a prop to your main react component ?

hurricanenate

hurricanenate OP

Yeah, that approach definitely works. I was hoping for a more integrated solution that doesn’t require those kinds of explicit pass-throughs.

hurricanenate

hurricanenate OP

This approach may make the most sense: my colleague was recommending we try an SSR-like approach using Phoenix’s render_to_string method, and it looks like ReactRender basically is a more fully realized version of that approach: I’ll be giving that a try today.

I am curious about the previous backend, and how it was working before.

The SPA also interacts with a separate go app via rest endpoints, and will continue to do so. We’re adding the Phoenix app as a way of giving this app the ability to handle its own separate, user-related concerns, which is why adding authentication is our first step.

kokolegorille

kokolegorille

This is how I would do with a Phoenix Backend, either REST or GraphQL, with Absinthe.

But I don’t see how You want to procede… using phx.gen.auth is not done for API.

And SPA have their own router, their own authentication, usually with a Phoenix Token.

Unless You want to use Phoenix, with React as the View layer.

You can pass data from backend to frontend via data attributes, even json encoded attributes, that You could parse JS side.

You can use Hooks if You use liveview, as a way to interact with JS.

bpaulino0

bpaulino0

Probably very late on the topic, but back in 2022, I wrote a blogpost on how to integrate the entire React pipeline within Phoenix so you can have a decent developer experience, but also a reasonable deployment pipeline that does not compromise on your current Elixir/Phoenix build steps.

I think the most challenging part is to make sure that you have a up2date build step for your SPA app and at the same time you don’t change your Phoenix setup too much. And you only need NodeJS during build-time.

— All posts loaded —

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement