Search code examples
javascriptreactjsexpresspugcreate-react-app

Is it Possible to serve a Client Side React Component / Application in a server side Express Route?


I have an Node/Express backend that is using Pug.js to render a number of server side routes. The application is static at the moment and is a simple site.

I created an interactive "builder" component in React.js using CRA. It allows a site visitor to configure product interactively. The end goal is this:

when a site visitor hits the builder nav link, they would be taken to a page that would render my serverside templates to keep the look and feel of the site. However, In the content block I would want to render the react application that I have created.

I have looking for days and maybe am just not understanding what I am seeing.I am not sure if server side rendering, or proxying would make this work? i have tried the CRA proxy and have not gotten the result.

Folder structure image:

Folder Structure

If anyone needs more info or can point out a few resources it would be very helpful.

I am still learning as well so I apologize if this breaks any SO guidelines.

Thank you in advance


Solution

  • So, your CRA looks something like

      import React from 'react';
        import ReactDOM  from 'react-dom';
    
        ReactDOM.render(
            <h1>Hello, world!</h1>,
            document.getElementById('app')
        );
    

    So to expose this component, you should have a pug template that is like all your others, except also contains somewhere in it

    <div id="app"></div>
    <script src="bundle.js"></script>
    

    Where the src of the script is the relative path to your built component. Then just serve that template with express when they hit that route.