Search code examples
apisveltesapper

Svelte/Sapper fetch/this.fetch is not defined in Server side API


Here is my question about using Svelte/Sapper

  • I have a file in /src/routes/login.js
  • According to Sapper doc, it will create an API endpoint in http://<my_domain>/login, which it does
  • Now in login.js, I would like to call another API server, assume that it is http://another_server/auth
  • No matter how I use the fetch function: fetch("http://another_server/auth"), this.fetch("http://another_server/auth"), Svelte responses: (this.)fetch is not defined.
  • The documentation said that it should be run within preload(), so I wrap the fetch under export async function preload(){}, it did not work

So my question is: other than using axios, can I keep on using fetch in server side API request?

Just tested in the template [slug].json.js file, when I add the (this.)fetch function, it did not compile, same error: (this.)fetch is not defined

Thank you very much.


Solution

  • Install the node-fetch npm package and use that in your server routes instead of the default fetch.

    (in /src/routes/login.js):

    import fetch from 'node-fetch'
    ...
    // inside your route handler
    const response = await fetch('http://another_server/auth') // no error
    

    If you are unsure if the code will be executed on the client-side or the server-side (i.e. you're looking for a universal/isomorphic approach) you can use a conditional require:

    // inside your route handler
    const fetch = process.browser ? window.fetch : require('node-fetch').default
    const response = await fetch('http://another_server/auth') // no error
    

    But this is probably overkill in your use case since server routes are by definition executed on the server side.