Understanding How Forward and Reverse Proxy Work
Tags: backenddevelopment, webdev, typescript, programming
Published: 2023-09-08 10:36:43

## What is a Proxy Server?

**A proxy** is a server that acts as an intermediary between clients (such as web browsers or applications) and servers (your backend). It facilitates communication between them while adding various functionalities like security, caching, load balancing, or anonymity. In other words, a proxy server is a middleware or middle-man between the client and the server.

Imagine a proxy server like a middle-person or a messenger that helps when you want to communicate with someone else, like sending a letter through a friend.


### Terminologies we'll be using in this article
**Clients:** These are like you when you use the internet. It could be your web browser, a mobile app, or any device that wants to talk to a website or an online service.

**Servers:** These are like the websites and services you visit on the internet. When you open a web page or use an app, you connect to a server with the information you need. The server here talks about the backend behind the things you see on the website, web app or mobile application

**Proxy Server:** The proxy server is the helpful middle-person. When you want to talk to a website or service, you don't talk directly to it. Instead, you talk to the proxy server and it handles all your requests on your behalf.


_Now, let's delve deep, shall we 😊?_


![Forward and Reverse Proxy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p5cm4j4oki9g006346ml.png)

## What is Forward Proxy and how does it work?

**_A Forward Proxy_**, often simply referred to as a _proxy server_ is positioned on the client-side of the network. It serves as a gateway for client devices to access resources on the internet, primarily providing anonymity and caching benefits.

**_Here is how a forward proxy works:_**
**_Client Request:_** When a client (e.g., a web browser) makes a request to access a resource on the internet, it sends the request to the forward proxy server instead of directly connecting to the target server.

**_Proxy Server Handling:_** The forward proxy server receives the client's request and forwards it on behalf of the client to the target server.

**_Response Relay:_** The target server processes the request and sends the response back to the forward proxy server.

**_Client Response:_** The forward proxy server, upon receiving the response, forwards it to the client.

## Code Sample in Node Ts (Node + TypeScript)

![Forward Proxy in Node and TypeScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v279z1oglgxkuuekcjdw.png)


```typescript
import http from 'http';

const forwardProxy = http.createServer((clientReq, clientRes) => {
  // Replace with the actual target server's hostname and port
  const targetServerOptions = {
    hostname: 'example.com',
    port: 80,
    path: clientReq.url,
    method: clientReq.method,
    headers: clientReq.headers,
  };

  const targetReq = http.request(targetServerOptions, (targetRes) => {
    clientRes.writeHead(targetRes.statusCode || 500, targetRes.headers);
    targetRes.pipe(clientRes, { end: true });
  });

  clientReq.pipe(targetReq, { end: true });

  targetReq.on('error', (err) => {
    console.error(err);
    clientRes.end();
  });
});

const proxyPort = 8080;
forwardProxy.listen(proxyPort, () => {
  console.log(`Forward proxy server listening on port ${proxyPort}`);
});
```


## What is Reverse Proxy and how does it work?

**_A reverse proxy_**, on the other hand, is positioned on the server-side of the network. It serves as a gateway to distribute client requests to multiple backend servers based on various criteria like load balancing, SSL termination, or URL routing.


**_Here is how a reverse proxy works:_**

**_Client Request:_** A client sends a request to access a resource on a particular domain.

**_Reverse Proxy Routing:_** The reverse proxy server receives the client's request and determines which backend server should handle the request based on predefined rules.

**_Request Forwarding:_** The reverse proxy forwards the client's request to the selected backend server.

**_Backend Server Response:_** The backend server processes the request and sends the response back to the reverse proxy.

**_Response to Client:_** The reverse proxy then relays the response to the client.


### Code Sample in Node Ts (Node + TypeScript)

![Reverse Proxy in Node and TypeScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sz2zowvjnmt1f1jw8ohi.png)


```typescript
import http from 'http';
import httpProxy from 'http-proxy';

// Create a reverse proxy server
const reverseProxy = httpProxy.createProxyServer({});

// Define routing rules
const routingTable = {
  'example.com': 'http://localhost:3000', // Forward requests to a local server
};

const reverseProxyServer = http.createServer((clientReq, clientRes) => {
  const target = routingTable[clientReq.headers.host || ''];

  if (target) {
    // Forward the request to the appropriate backend server
    reverseProxy.web(clientReq, clientRes, { target });
  } else {
    // Handle errors or unknown routes
    clientRes.writeHead(404);
    clientRes.end('Not Found');
  }
});

const proxyPort = 80;
reverseProxyServer.listen(proxyPort, () => {
  console.log(`Reverse proxy server listening on port ${proxyPort}`);
});
```


---


So, to clarify, forward and reverse proxies are specific types of proxy servers, each with its own distinct role and functionality. the TypeScript examples I gave should give you a basic understanding of how forward and reverse proxy servers work. You can extend and customize these examples to meet your specific requirements or use existing libraries like http-proxy for more advanced features. If you have any questions as regards to this post, you can ask in the comment section below. Thanks for liking, sharing and following 😍. 


---


### Connect with me 🔥🔥🔥

[GitHub](https://github.com/emmanuelishola123/) 
[Twitter](https://twitter.com/EmmanuelIshola0/)
[LinkedIn](https://www.linkedin.com/in/emmanuelishola1/)
[Instagram](https://www.instagram.com/emmanuelishola1/)
[Facebook Page](https://web.facebook.com/solutionglobaltech)

Till the next post, Stay tuned 😍