Problem description
I would like to run a Netlify function in a Svelte app. However, during development, the requests for the function cannot be found (404). I assume this has to do with the port on which Netlify is serving the functions.
The issue only arises in development. When the app is deployed on Netlify, the function call works just fine. And it also works fine without Svelte.
I have used the basic Svelte template. My Netflify function is called "number" and just returns "42".
number.js:
const handler = async (event) => {
try {
return {
statusCode: 200,
body: JSON.stringify(42),
};
} catch (error) {
return { statusCode: 500, body: error.toString() };
}
};
module.exports = { handler };
When I run netlify dev
, this starts Netlify's development server with Svelte. It logs:
Loaded function number (http://localhost:8888/.netlify/functions/number).
◈ Functions server is listening on 52041
But http://localhost:8888/.netlify/functions/number
does give a 404. Only http://localhost:52041/.netlify/functions/number
works here. Can someone explain the first log then, isn't this just incorrect?
The problem now is that the functions port changes every time I call netlify dev
. We can fix this by changing the Netlify configuration file:
netlify.toml:
[build]
publish = "public/"
functions = "functions/"
[dev]
publish = "public/"
functions = "functions/"
port = 8080
functionsPort = 52041
In the end, I would like to add a button to my Svelte app which makes a fetch request to that function.
App.svelte:
<script>
async function getNumber() {
const url = `http://localhost:52041/.netlify/functions/number`;
const res = await fetch(url);
const data = await res.json();
window.alert(data);
}
</script>
<button on:click={getNumber}>Click me</button>
This works now in development, but not in production: Here the url should be /.netlify/functions/number
.
So my question is:
- How can we determine the correct URL which works in each case (dev/prod)?
- Is there a more elegant way to call a Netlify function in a Svelte app?
- In particular, is it possible to use the URL
/.netlify/functions/number
somehow in both cases (dev/prod)?
Related questions on the internet: