API behaves slowly in SvelteKit (Pusher, Vercel)

143 views Asked by At

The API referred to here is Pusher. (You don’t need to know anything about Pusher.)
Here's how to load the Pusher:

const pusher = new Pusher({
    appId: [id],
    key: [key],
    secret: [secret],
    cluster: "ap3",
    useTLS: true
});

Since this requires a secret key, I load it from +server.ts for security purposes.

// server.ts

import type { RequestHandler } from "./$types";
import Pusher from 'pusher';


export const POST:RequestHandler = async ({ request }) => {
    const pusher = new Pusher({
        appId: [id],
        key: [key],
        secret: [secret],
        cluster: "ap3",
        useTLS: true
    });

    const req = await request.json();
    const res = await pusher.trigger("chat", "message", req);

    return new Response((JSON.stringify({"result": res})), {
        headers:{
            'Content-Type': 'application/json'
        }
    })
}

Using this code will reload the Pusher every time you POST to the server.
However, considering that Pusher is an API used to build real-time, this is very slow. Each call consumes approximately 1 second.

It works immediately when run with 'npm run dev', but it is this slow only when deployed with Vercel.
I think this problem is caused by the time it takes to turn the servers on, since Vercel turns them off when they are not in use.

Wouldn't it be faster if you pre-load Pusher and simply use pusher.trigger in +page.svelte? Still the secret key must not be exposed.

Is there a way to load the API only once rather than each time the server is called?

0

There are 0 answers