Jerome Indefenzo Jerome Indefenzo - 1 year ago 207
React JSX Question

react + webpack - pass POST data to build

Coming from a PHP background, I used to have an index.php which does two things:

  1. serve the webpage if no parameters were set;

  2. or serve JSON data when a specific POST parameter was included in the request.

Something like this:

// -- index.php
if ($_POST["some_parameter"]) {
echo json_encode(someArrayData);


I have built the complete frontend application with npm, webpack, webpack-dev-server, and react. Having completed the first part, how can I effectively serve JSON data instead of HTML when a request includes a specific POST parameter?

I can see 2 ways of doing this:

  • Build the frontend as usual and everytime I build the bundle, modify
    , inject my PHP code in it, and rename it to index.php. I then would have to run this folder via apache or nginx, so I'd be able to run the index.php script. This method is downright ugly and is probably the worst way to do it.

  • Run a separate PHP server which just serves data or redirects to the static webpack-generated build. All requests should then start from this server, and this server determines whether to serve data or redirect to the frontend. The problem comes to neatly passing the POST data received from the request to the static react app. As far as I know, the only way to do this would be to include a URL (GET) parameter to the redirect and manually parse it with javascript on the frontend. This is a dirty solution, in my opinion.

So, to summarize:

  • I need an efficient way to get POST data in a react/webpack/webpack-dev-server environment.

  • It should work with my hot-module-replacement dev setup.

  • I'm fine with switching to a node-based backend like express.

  • There shouldn't be any ajax involved in the static react app.

Any ideas? There has to be a way to do this properly.

Answer Source

UPDATE: I solved this by simply copying an index.php from my source directory to my build directory via the webpack config. I serve the build folder to a PHP server and keep a webpack --watch building my source.

I lose built-in features like auto-reload and css injection, but it's worth the convenience of not having to implement SSR for a very simple task (getting a single POST variable).

For anyone interested, I also added 2 npm scripts:

  • npm run start runs my original webpack-dev-server with hot-reload, serving static content including a static index.html file
  • npm run static runs the webpack --watch which copies the index.php file to the build directory

This lets me have hot-reloading when developing frontend, and allows POST data fetching when programming logic.

It's easy, convenient, and works on most web hosting providers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download