Sling Academy
Home/Node.js/How to create a proxy server with Node.js (TypeScript example)

How to create a proxy server with Node.js (TypeScript example)

Last updated: January 01, 2024

Introduction

Building a proxy server with Node.js and TypeScript can serve as a gateway between users and the internet, improving security and performance. This tutorial will guide you step-by-step through the process.

Setting Up the Project

To start, make sure you have Node.js installed on your system. Then, initialize a new Node.js project and install the TypeScript compiler by running:

npm init -y
npm install typescript --save-dev

Create a tsconfig.json file to configure TypeScript options:

{
    "compilerOptions": {
        "module": "commonjs",
        "esModuleInterop": true,
        "target": "es6",
        "noImplicitAny": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "outDir": "dist"
    },
    "include": [
        "src/**/*.ts"
    ]
}

Install Proxy Libraries

Next, install the http-proxy library, which will handle the proxying of requests:

npm install http-proxy

Basic Proxy Server

Create a server.ts file in the src directory and add the following code to set up a basic proxy server:

import * as http from 'http';
import * as httpProxy from 'http-proxy';

const proxy = httpProxy.createProxyServer({});
const server = http.createServer((req, res) => {
    proxy.web(req, res, { target: 'http://example.com' });
});

server.listen(3000, () => {
    console.log('Proxy server listening on port 3000');
});

Handling Errors

To handle proxy server errors, add an event listener:

proxy.on('error', (err, req, res) => {
    // Handle error here
    res.writeHead(500, {
        'Content-Type': 'text/plain'
    });
    res.end('Something went wrong.');
});

Adding Middleware

Middlewares allow you to intercept and modify requests and responses. For example:

// ... previous code

server.on('request', (req, res) => {
    // Modify request headers
    req.headers['X-Special-Proxy-Header'] = 'foobar';

    proxy.web(req, res);
});

Advanced Configuration

To handle HTTPS requests or add custom routing logic, extend the proxy server’s functionality. Install required packages and update your proxy configuration:

npm install https

Update the server.ts:

// ... previous imports
import * as https from 'https';
import * as fs from 'fs';

const sslOptions = {
    key: fs.readFileSync('path/to/your/key.pem'),
    cert: fs.readFileSync('path/to/your/cert.pem')
};

const httpsServer = https.createServer(sslOptions, (req, res) => {
    // Handle HTTPS requests
    proxy.web(req, res);
});

httpsServer.listen(3443, () => {
    console.log('HTTPS proxy server listening on port 3443');
});

Running the Proxy Server

Compile the TypeScript code with tsc and start the proxy server:

tsc
node dist/server.js

Testing Your Proxy Server

Test the server using a web browser or tools like curl to make sure it is proxying requests correctly:

curl http://localhost:3000

Conclusion

A proxy server in Node.js with TypeScript provides a flexible solution for traffic routing. By following this guide, you can extend and adapt the proxy server to your specific needs, ensuring enhanced security and efficiency.

Next Article: How to Use WebSockets for Real-Time Communication in Node.js

Previous Article: How to Setup a Node.js Cluster for Speed & Stability

Series: Node.js Intermediate Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates