Search code examples
sveltesveltekit

I'm getting an error in "Serverless Function" in my SvelteKit Project often


I don't know why I'm getting this error sometimes.

504: GATEWAY_TIMEOUT
Code: FUNCTION_INVOCATION_TIMEOUT

I'm using the load function to fetch the posts on the index page.

<script context="module">
    export async function load({ page, fetch }) {
        const pagination = page.query.get('page') ?? 1;

        let PER_PAGE = 2;
        // calculate start page
        let startPage = +pagination === 1 ? 0 : (+pagination - 1) * PER_PAGE;

        // fetch total/count
        const totalUrl = `https://myblog.herokuapp.com/posts/count`;
        const totalRes = await fetch(totalUrl);

        // fecth articles
        const url = `https://sveltestrapiblog.herokuapp.com/posts?_sort=created_at:DESC&_start=${startPage}&_limit=${PER_PAGE}`;

        const articelRes = await fetch(url);

        if (articelRes.ok && totalRes.ok) {
            return {
                props: {
                    posts: await articelRes.json(),
                    total: await totalRes.json(),
                    pagination: +pagination
                }
            };
        }

        return {
            status: articelRes.status,
            error: new Error(`Could not load ${url}`)
        };
    }
</script>

I don't know what's wrong.


Solution

  • When you deploy a SvelteKit app, it uses a serverless function to handle incoming requests and render the HTML for each page. When you deploy to a provider like Netlify or Vercel, they limit how long these functions can run. On Vercel, the limit is 5 seconds for the Hobby Plan and Netlify's limit is 10 seconds. If your page render takes longer than this limit, you will receive the FUNCTION_INVOCATION_TIMEOUT error.

    I noticed your API at https://sveltestrapiblog.herokuapp.com/posts takes some time to return a response the first time I hit it, likely because it is starting up after a period of inactivity. When this happens, you will see an error if you take longer than the execution time limit. You will either need to handle this error or make sure your API can always return a response in under 5 seconds.