Skip to content

Setup/Config Proxy Server #33

@travisjupp

Description

@travisjupp

Problem: Requests -- not limited to, but mainly on mobile platforms -- are most likely running into CORS 403 errors due to requests being made directly from the frontend.

Solution: Create a Backend Proxy server for server-to-server communication to avoid CORS 403.

Origin https://react-reddit-client.netlify.app is not allowed by Access-Control-Allow-Origin. Status code: 403
Fetch API cannot load https://www.reddit.com/r/popular.json due to access control checks.
Failed to load resource: Origin https://react-reddit-client.netlify.app is not allowed by Access-Control-Allow-Origin. Status code: 403

Implement Proxy Server on Netlify

  • Create Serverless Proxy function

A typical proxy function would receive a request from your frontend, make a request to the external API, and return the response.

// netlify/functions/proxy.js
const fetch = require('node-fetch');

exports.handler = async (event) => {
  const response = await fetch('https://external-api.com/data');
  const data = await response.json();
  return {
    statusCode: 200,
    body: JSON.stringify(data),
  };
};
// You would call this function from your frontend at /.netlify/functions/proxy, and it would forward the request to the external API, returning the result to your frontend.
  • Run Frontend and Serverless functions locally (Netlify CLI netlify dev)
    Function available at: http://localhost:8888/.netlify/functions/reddit-proxy

  • Deploy
    Push to repo, deploy is triggered on Netlify. Function is live at:
    https://react-reddit-client.netlify.app/.netlify/functions/reddit-proxy?subreddit=popular

https://docs.netlify.com/build/caching/caching-overview/
https://www.netlify.com/blog/introducing-netlify-cache-api/
https://www.netlify.com/blog/durable-cache-quest-for-fast-fresh-content/

Metadata

Metadata

Assignees

Labels

backendSetup/Management of cloud-based tools and services including data-storage, auth, hosting etc..

Projects

Status

In Progress

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions