Elevating React: Unleashing the Power of Nginx for Effortless Deployment
Tags: javascript, tutorial, react, nginx
Published: 2023-12-09 07:50:19

In the dynamic world of web development, efficient implementation of React applications is critical to providing a smooth user experience. One powerful tool that can greatly improve the deployment process is Nginx. 
In this blog post, we'll explore the benefits of using Nginx to deploy React applications, introduce its features that make deployment easier, and provide a step-by-step guide to help you integrate Nginx into your React deployment pipeline.

## Why Nginx?
Choosing Nginx for deploying React applications is a strategic decision rooted in its robust capabilities. Nginx's efficient load balancing ensures seamless distribution of user requests, optimizing performance, and preventing server overload. Its built-in caching mechanisms significantly enhance load times, providing users with a faster and more responsive experience. Moreover, Nginx's versatility as a reverse proxy and its ability to handle SSL termination make it a reliable choice for securing and scaling React applications. In summary, Nginx's powerful features make it a compelling and practical solution for elevating the deployment of React applications.

## Integrating Nginx into Your React Deployment
### Step-1: Installing Nginx in the VM server
 
```
sudo apt update
sudo apt install ngnix
```
After installation, to start the nginx service first adjust the firewall by - 
```
sudo ufw app list
sudo ufw allow 'Nginx HTTP'
sudo ufw status
```
And to check if ngnix service status
```
systemctl status nginx
```

### Step-2: Preparing UI

When the previous development is complete, run **"npm build"** to compile and optimize your React application for production and create an improved version ready for deployment.

### Step-3: Adding build folder and setting up reverse proxy in nginx

Two input files required to change which can be found in /etc/nginx/ that are 
- sites-enabled/default
- nginx.conf

`$ cat /etc/nginx/sites-enabled/default`

```javascript
server {
	listen 80 default_server;
	listen [::]:80 default_server;

	root /usr/share/nginx/html;

	index index.html index.htm index.nginx-debian.html;

	server_name _;
	client_max_body_size 5M;
	location /static {
	    alias /usr/share/nginx/html/static;
    }
	 location /favicon.ico {
		alias /usr/share/nginx/html/favicon.ico;
	}
	location / {   //Root Location
			try_files $uri /index.html;
		}
	location /v1/ {  //Proxy to Backend Location         
	proxy_pass http://101.244.148.101:5003; 
        proxy_buffering off;
    	proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;

	}
}
```
In above code,

- `root /usr/share/nginx/html` - Specifies the root directory for the server, where it will look for files to serve.

- `index index.html index.htm index.nginx-debian.html;` - Defines the order in which index files are tried when a directory is accessed. For example, if a user requests a directory, Nginx will try to serve index.html first.

- `location / {}` - This block is used to handle general requests. If the requested file doesn't exist, it falls back to serving `/index.html`.


- `location /v1/{}` - This block is used to proxy requests with the path prefix /v1/ to a backend server at http://101.244.148.101:5003. It also sets some headers (`X-Real-IP`, `X-Forwarded-Host`, `X-Forwarded-Port`) to preserve client information when passing the request to the backend serve

After making changes, then we will make changes in nginx configuration file.

`$ cat /etc/nginx/nginx.conf`

Add this code block inside "http{}"

```javascript
http{
...                  //default code 
add_header X-Frame-Options "SAMEORIGIN";
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload";
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
add_header X-XSS-Protection "1; mode=block";
proxy_hide_header X-Powered-By;
etag off;
...                //default code
}
```

- **add_header X-Frame-Options "SAMEORIGIN";**
    - Specifies the X-Frame-Options header to mitigate clickjacking attacks.

- **add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload"**
   - Configures HTTP Strict Transport Security (HSTS) to enforce secure connections over HTTPS.

- **add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;**
   - Defines a Content Security Policy (CSP) to mitigate cross-site scripting (XSS) attacks.

- **add_header X-XSS-Protection "1; mode=block";**
   - Enables the browser's built-in Cross-Site Scripting (XSS) protection.

- **proxy_hide_header X-Powered-By;**
     - Hides the X-Powered-By header in responses from proxied servers.
     - Enhances security by reducing information about the server software.

- **etag off;**
   - Disables the use of Entity Tags (ETags) in HTTP responses.
   - ETags are used for web cache validation; disabling them can improve performance and reduce unnecessary server load.


After saving the file, copy for **build** folder content inside `/usr/share/nginx/html`

Restart the nginx service by - `sudo systemctl reload nginx`

You can now access your website or application through your browser.

If any issues arise, check the Nginx error logs for potential error messages.

## Conclusion:
By seamlessly integrating Nginx into your React deployment strategy, you unlock a suite of powerful tools that not only boost performance and security but also scale your application seamlessly. This post offers a comprehensive overview of Nginx's capabilities, coupled with a step-by-step guide for effortless integration into your React deployment pipeline. 

**_Happy Coding!!_**