Search code examples
sveltesapper

Svelte/Sapper How to fetch data from internal api without giving absolute URL


I am using svelte/sapper with express.

I have an api in routes/billing/index.js

It needs to fetch data from customers/[customernumber]/detections.js

My question is how to fetch data from internal apis with in the routes folder using relative URLs

async function getDataFromGateway(customerNumber) {
  if (typeof fetch !== 'function') {
    global.fetch = require('node-fetch')
  }
  const data = await fetch(`http://localhost:19052/customers/${customerNumber}/detections`)
    .then(res => res.json())
    .catch(error => {
      console.log(error)
      return error
    }
    )
  return data
}

Is there a way to do this using relative url


Solution

  • The easiest way is to fetch this data inside preload, using this.fetch, since that will automatically handle relative URLs the same way whether it's running on server or client:

    <script context="module">
      export async function preload(page, session) {
        const r = await this.fetch(`customers/${getCustomerNumber(session)}/detections`);
        const data = await r.json();
    
        return {
          foo: data.foo
        };
      }
    </script>
    

    If that's not possible for whatever reason, you might need to configure an environment variable, e.g. BASE_URL:

    async function getDataFromGateway(customerNumber) {
      if (typeof fetch !== 'function') {
        global.fetch = require('node-fetch')
      }
      const data = await fetch(`${process.env.BASE_URL}/customers/${customerNumber}/detections`)
        .then(res => res.json())
        .catch(error => {
          console.log(error)
          return error
        }
        )
      return data
    }