Edgio with middleware

Hi everyone,

I’m new with Edgio and I can’t figure out how to add a middleware in order to modify requests headers and responses
I also need to interrogate an API and depending on the response it will add new headers to the request
Is it possible to achieve such behavior?
Thanks for your help

I’d take a look at these 2 examples for altering the request and response: Common Routing Patterns | Edgio Documentation

You can define a route pattern you wish to match, and then in the handler, you can set/update/remove headers for the request and response.

The same approach can be taken for the API you want to integrate. You can define an existing API endpoint within the edgio.config.js file under backends like so:

backends: {
  api: {
    // The domain name or IP address of the origin server
    domainOrIp: "api.mysite.com",

    // When provided, the following value will be sent as the host header 
    // when connecting to the origin. If omitted, the host header from 
    // the browser will be forwarded to the origin.
    hostHeader: "api.mysite.com",
  }
}

And in the router, you can match any requests coming in for /api/*, set a request header, and continue to proxy the request to your upstream API endpoint:

// will match all requests to /api/*, set a request header, and proxy the request to the origin API endpoint
router.match('/api/:path*', ({ proxy, setRequestHeader }) => {
  setRequestHeader('x-my-header', 'foo')

  // proxies the request to the `api` backend with the modified request header
  proxy('api')
})

This is just a basic example. Let me know if there are more details and I can give you a more comprehensive example for your use case.

hi @tristan.lee
Thanks for your feedback.
My apologies I wasn’t clear enough regarding what I would achieve at the end.
The main idea is to read the original request, call an 3rd party API to retrieve some data, and then set some headers in the original request and responses if possible

I’ve try something based on next.js but I m not sure this is an ideal way to do it. Maybe compute()?

Thanks

In that case, I would suggest compute() as well. You can provide it an async function so this is where you could call your API, wait for the response, and modify the response as desired.

This example uses compute(async (req, res) => {}) to determine where to redirect to. You should be able to follow similar pattern. Common Routing Patterns | Edgio Documentation

Feel free to provide a code sample if you get stuck and we’ll figure it out.