[javascript] How to deploy a React App on Apache web server

I have created a basic React App from https://www.tutorialspoint.com/reactjs/reactjs_jsx.htm here , I want to run this test code on Apache based server, I know that I need to create a distributable build but I am not able to figure out how to do that and couldnt find clear instructions.

I have seen this post React,js on Apache server but it doesn't have anything more than few guidelines

This question is related to javascript apache reactjs

The answer is


Firstly, in your react project go to your package.json and adjust this line line of code to match your destination domain address + folder:

"homepage": "https://yourwebsite.com/your_folder_name/",

Secondly, go to terminal in your react project and type:

npm run build

Now, take all files from that newly created build folder and upload them into your_folder_name, with filezilla in subfolder like this:

public_html/your_folder_name

Check in the browser!


As well described in React's official docs, If you use routers that use the HTML5 pushState history API under the hood, you just need to below content to .htaccess file in public directory of your react-app.

Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [QSA,L]

And if using relative path update the package.json like this:

"homepage": ".",

Note: If you are using react-router@^4, you can root <Link> using the basename prop on any <Router>.

import React from 'react';
import BrowserRouter as Router from 'react-router-dom';
...
<Router basename="/calendar"/>
<Link to="/today"/>

  1. Go to your project root directory cd example /home/ubuntu/react-js
  2. Build your project first npm run build
  3. check your build directory gracefully all the files will be available in the build folder.

    asset-manifest.json

    favicon.ico

    manifest.json

    robots.txt

    static assets

    index.html

    precache-manifest.ddafca92870314adfea99542e1331500.js service-worker.js

4.copy the build folder to your apache server i.e /var/www/html

sudo cp -rf build /var/www/html
  1. go to sites-available directory

    cd /etc/apache2/sites-available/

  2. open 000-default.conf file

    sudo vi 000-default.conf and rechange the DocumentRoot path

    enter image description here

  3. Now goto apache conf.

    cd /etc/aapche2

    sudo vi apache2.conf

    add the given snippet

_x000D_
_x000D_
<Directory /var/www/html>_x000D_
_x000D_
            Options Indexes FollowSymLinks_x000D_
_x000D_
            AllowOverride All_x000D_
_x000D_
            Require all granted_x000D_
_x000D_
    </Directory>
_x000D_
_x000D_
_x000D_

  1. make a file inside /var/www/html/build

    sudo vi .htaccess

_x000D_
_x000D_
Options -MultiViews_x000D_
    _x000D_
RewriteEngine On_x000D_
    _x000D_
RewriteCond %{REQUEST_FILENAME} !-f_x000D_
_x000D_
RewriteRule ^ index.html [QSA,L]
_x000D_
_x000D_
_x000D_

9.sudo a2enmod rewrite

10.sudo systemctl restart apache2

  1. restart apache server

    sudo service apache2 restart

    thanks, enjoy your day


As said in the post, React is a browser based technology. It only renders a view in an HTML document.

To be able to have access to your "React App", you need to:

  1. Bundle your React app in a bundle
  2. Have Apache pointing to your html file in your server, and allowing access externally.

You might have all the informations here: https://httpd.apache.org/docs/trunk/getting-started.html for the Apache server, and here to make your javascript bundle https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr


First, add a pom.xml and make it a maven project and then build it. It will create a War file for you in the target folder after that you can deploy it wherever you want.

pom.xml http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 it.megadix create-react-app-servlet 0.0.1-SNAPSHOT war

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <npm.output.directory>build</npm.output.directory>
</properties>

<build>
    <finalName>${project.artifactId}</finalName>
    <plugins>
        <!-- Standard plugin to generate WAR -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <webResources>
                    <resource>
                        <directory>${npm.output.directory}</directory>
                    </resource>
                </webResources>
                <webXml>${basedir}/web.xml</webXml>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.3.2</version>
            <executions>
                <!-- Required: The following will ensure `npm install` is called
                     before anything else during the 'Default Lifecycle' -->
                <execution>
                    <id>npm install (initialize)</id>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                    <phase>initialize</phase>
                    <configuration>
                        <executable>npm</executable>
                        <arguments>
                            <argument>install</argument>
                        </arguments>
                    </configuration>
                </execution>
                <!-- Required: The following will ensure `npm install` is called
                     before anything else during the 'Clean Lifecycle' -->
                <execution>
                    <id>npm install (clean)</id>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                    <phase>pre-clean</phase>
                    <configuration>
                        <executable>npm</executable>
                        <arguments>
                            <argument>install</argument>
                        </arguments>
                    </configuration>
                </execution>

                <!-- Required: This following calls `npm run build` where 'build' is
                     the script name I used in my project, change this if yours is
                         different -->
                <execution>
                    <id>npm run build (compile)</id>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                    <phase>compile</phase>
                    <configuration>
                        <executable>npm</executable>
                        <arguments>
                            <argument>run</argument>
                            <argument>build</argument>
                        </arguments>
                    </configuration>
                </execution>

            </executions>

            <configuration>
                <environmentVariables>
                    <CI>true</CI>
                    <!-- The following parameters create an NPM sandbox for CI -->
                    <NPM_CONFIG_PREFIX>${basedir}/npm</NPM_CONFIG_PREFIX>
                    <NPM_CONFIG_CACHE>${NPM_CONFIG_PREFIX}/cache</NPM_CONFIG_CACHE>
                    <NPM_CONFIG_TMP>${project.build.directory}/npmtmp</NPM_CONFIG_TMP>
                </environmentVariables>
            </configuration>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>local</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>

                    <configuration>
                        <environmentVariables>
                            <PUBLIC_URL>http://localhost:8080/${project.artifactId}</PUBLIC_URL>
                            <REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
                        </environmentVariables>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

    <profile>
        <id>prod</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>

                    <configuration>
                        <environmentVariables>
                            <PUBLIC_URL>http://my-awesome-production-host/${project.artifactId}</PUBLIC_URL>
                            <REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
                        </environmentVariables>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

Note:- If you find a blank page after running your project then clear your cache or restart your IDE.


Before making the npm build,
1) Go to your React project root folder and open package.json.
2) Add "homepage" attribute to package.json

  • if you want to provide absolute path

    "homepage": "http://hostName.com/appLocation",
    "name": "react-app",
    "version": "1.1.0",
    
  • if you want to provide relative path

    "homepage": "./",
    "name": "react-app",
    

    Using relative path method may warn a syntax validation error in your IDE. But the build is made without any errors during compilation.

3) Save the package.json , and in terminal run npm run-script build
4) Copy the contents of build/ folder to your server directory.

PS: It is easy to use relative path method if you want to change the build file location in your server frequently.


You can run it through the Apache proxy, but it would have to be running in a virtual directory (e.g. http://mysite.something/myreactapp ).

This may seem sort of redundant but if you have other pages that are not part of your React app (e.g. PHP pages), you can serve everything via port 80 and make it apear that the whole thing is a cohesive website.

1.) Start your react app with npm run, or whatever command you are using to start the node server. Assuming it is running on http://127.0.0.1:8080

2.) Edit httpd-proxy.conf and add:

ProxyRequests On
ProxyVia On
<Proxy *>
  Order deny,allow
  Allow from all
  </Proxy>

ProxyPass /myreactapp http://127.0.0.1:8080/
ProxyPassReverse /myreactapp  http://127.0.0.1:8080/

3.) Restart Apache


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to apache

Enable PHP Apache2 Switch php versions on commandline ubuntu 16.04 Laravel: PDOException: could not find driver How to deploy a React App on Apache web server Apache POI error loading XSSFWorkbook class How to enable directory listing in apache web server Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details How to enable php7 module in apache? java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release