Symfony4 backend with frontend react. best and safest way to pass information?

Viewed 1022

I am learning React and want to create an application with Symfony4 as my backend and React frontend. I am stuck now when I need to pass some kind of data to the frontend from my backend. I don't really know what is the right way to do it? Following some tutorials I am doing it like this:

From the controller I send some data to the twig file:

/**
 * @Route("/")
 */
public function homepage()
{
    $date = new DateTime();
    $curr_date = $date->format('Y-m-d H:i:s');

    return $this->render('base.html.twig', [
        'gameDate' => $curr_date
    ]);
}

In the twig file, I set it as a data-attribute

base.html.twig:

<div id="root" data-event-date="{{ gameDate }}">

Then I can get the variable as a dataset in my JavaScript

App.js:

const root = document.getElementById('root');

ReactDOM.render(<Homepage {...(root.dataset)}/>, root);

And render it from props.

Homepage.js:

class Homepage extends Component {
    constructor(props) {
        super(props)
        this.state = {
            prizePool: '',
            gameDate: '',
            numberOfPlayers: '' 
        }
    }

    onParticipateClick = (event) => {
        this.setState({prizePool: Math.random()})
    }

    render()
    {
        return (
            <div className="mt-c-10">
                 <GameInfoBox gameDate={this.props.eventDate}/>
            </div>
        )
    }
}

This actually works, but I am concerned with showing all the information in data variables because anyone can see it. What if I want to pass user ID or something secret? There should be another way to do it right?

2 Answers

"Best and safest" is a little ambiguous - do you need strict security, or safe as in code stability etc?

Instead of passing your data from controller to view (twig) and then into HTML elements or global, another way is this:

  1. Controller loads the view file with your nav and other stuff
  2. Controller loads React (however you do this, Webpack etc)
  3. React calls another controller (i.e. fetch()). This controller is probably somewhere like src/Api/Controller/ as it wont render a view so keep it separate to the other controllers which do render a view
  4. The API controller calls your DB or remote API (etc) and gets the data and sends it back as JsonResponse back to React.
  5. React can then show the data, or an error message depending on the response status

The API controller in your MW can also handle errors and do some logging, so React just gets a 200 and the data or a 400 (or whatever) and it can show a nice message to the user as normal.

Related