How to create proxy on Netlify functions?

I would like to build a website. Due to the CORS problem I would need a proxy for all my requests. I would like to use Netlify Functions as the proxy.

Instead of writing several Netlify Functions that make requests to different servers, I would like to create a Netlify Functions that serves as a proxy and make all requests using that proxy Netlify Functions.

I’d like to know if there are some Netlify Functions sample code that serves as proxy? Thanks in advance.

Hey @winstonma,
This person had a similar question. Do you want to take a look at the suggestion there and let us know if it works for you or if you have questions?

Thanks @jen

The CORS problem is not only in the dev environment but also in publish environment. So I am afraid that doesn’t work.Therefore I would like to have a proxy in netlify function. I would look like this

Input: .netlify/xxx/http://www.google.com

Then the netlify function would parse the URL (http://www.google.com) on behalf of the browser and return the parsed value back to the browser. This would be running in the production site.

Hey @winstonma,
I know the title of that post says it’s only for Netlify Dev, but you’d publish the same function to production and be in business! The way it works is:

  1. you call the function
  2. the function makes the API request
  3. the function returns the API response to you

If you want to do something more like what you described, you could try something like:

[[redirects]]
from="/call-proxy/*"
to="/.netlify/functions/whatever-your-function-name/:splat"
status=301

and log the url using console.log(event.path).

Let us know how it goes!

@jen Thanks for the reply. I will give it a try.

@jen Actually I don’t want to do my proxy thing. I just want to get the API called directly from the browser and have no CORS problem.

@jen I tried the fetch in the link you posted. It worked flawlessly.

However when I tried to replace https://icanhazdadjoke.com with my URL, the error comes. So I guess this fetch way won’t work for me.

Currently I have a netlify function that already work but I still think putting all the fetching logic in the front end and then build a proxy function would allow me to maintain less code.