How to deploy Symfony 4 backend (in subdirectory) with React frontend

Viewed 775

So, I am trying to build an platform that uses Symfony 4 as a backend service (only JSON api calls) and React as the frontend.

I am using cPanel and after building my React app in production mode I copy it in the public_html folder.

At the same time I create a folder called 'api' and throw Symfony backend code there. I've installed symfony/apache-pack and I can access my Symfony API at the following URL: 'mydomain.com/api/public/api/users' since the htaccess file that apache-pack created is located in the public folder.

However this is not what I want, I'd like to be able to access my API as 'mydomain.com/api/users' and also be able to reach React app by 'mydomain.com/login' (or any other route I create).

Is there any config I can do to make this work?

Should I simply switch my Symfony app to a subdomain like 'api.domain.com' and use that?

1 Answers

You'd be surprised this is very simple, and applies not just to react but any other JavaScript framework that you want to combine with Symfony.

Just add the react index.html to becomes symfony's base.html.

In other words let Symfony Render the index.html where you reference React Scripts

../base.html.twig

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>My React App</title>
  </head>
  <body>
    <!-- ... other HTML ... -->

    <!-- Load React. -->
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

    <!-- Load our React component. -->
    <script src="app.js"></script>

  </body>
</html>
Related