How to set up your own CORS proxy server?

10.12.2023 21:43

CORS (Cross-Origin Resource Sharing) — this is a mechanism that allows web pages to request resources from a different domain than the one the web page itself belongs to. A proxy server that adds CORS headers to the response allows bypassing restrictions associated with the same-origin policy.

Sometimes you may encounter a situation where you need to access resources that do not support CORS. In such cases, a proxy server can be used to add the necessary CORS headers to the responses, thereby bypassing the same-origin policy restrictions. This can be useful during development or when working with external APIs that, for some reason, do not include CORS support.

To set up your own CORS proxy server, you will need:

  • A VPS server or hosting with the ability to install node.js;
  • A domain or subdomain for installing SSL Let’s Encrypt.

Installation Instructions

Create a subdomain, for example, cors.example.com. Issue and install SSL Let’s Encrypt for it. This step is optional; you can use the proxy without SSL, but then when requesting sites with SSL, you will receive a «mixed content» error.

  1. Install Node.js and npm on your OS
  2. In the created site directory (for example, public_html), install the express and cors-anywhere packages.
                        
    
    npm install express cors-anywhere
  3. Create a server file server.js in the project folder and add the following code:
                        
    
    const express = require('express');
    const corsAnywhere = require('cors-anywhere');
    
    // Create an instance of the proxy server
    const proxy = corsAnywhere.createServer({
        originWhitelist: [], // Allow all sources
        requireHeader: [],
        removeHeaders: []
    });
    
    // Create an instance of Express
    const app = express();
    
    // Use the proxy server at a specific path, for example, "/proxy"
    app.use('/proxy', (req, res) => {
        req.url = req.url.replace('/proxy/', '/'); // Strip '/proxy' from the URL
        proxy.emit('request', req, res);
    });
    
    // Start the server
    const port = process.env.PORT || 8080;
    app.listen(port, () => {
        console.log(CORS Proxy running on port ${port});
    });
  4. Start the server.

That’s it! Your own CORS proxy server is ready. To keep it running after closing the terminal, use the Tmux utility or other background work solutions.

© 2024 az-dd.com | Nuxt.js & Tailwind CSS & Wordpress