Search code examples
proxystatic-sitenetlifycross-sitejamstack

How do I proxy API requests in a JAMstack solution?


I'm developing a site that's virtually entirely static. I use a generator to create all the HTML.

However, my site is a front-end to a store embedded in its pages. I have a little node.js server proxying requests on behalf of the browser to the back-end store. All it does is provide the number of items in the shopping cart so I can keep the number updated on all pages of my site. That's because the browser doesn't allow cross-domain scripting. My server has to act as a proxy between the client and the store.

(The embedded store is loaded from the store's web site and so itself does not require proxying.)

I was hoping to eventually deploy to Netlify or some similar JAMstack provider. But I don't see how I'd proxy on Netlify.

What is the standard solution to this problem? Or is proxying unavailable to JAMstack solutions? Are there JAMstack providers that solve this problem?


Solution

  • Netlify does allow for proxy rewrites using redirect paths with status code 200.

    You can store your proxy redirects in _redirects at the root of your deployed site. In other words the file needs to exist at the root of the site directory to be deployed after a build.

    _redirects /api/* https://api.example.com/:splat 200

    So a call to:

    /api/v1/gifs/random?tag=cat&api_key=your_api_key
    

    will be proxied to:

    https://api.example.com/v1/gifs/random?tag=cat&api_key=your_api_key
    

    If the API supports standard HTTP caching mechanisms like Etags or Last-Modified headers, the responses will even get cached by CDN nodes.

    NOTE: you can also setup your redirects in your netlify.toml