sveltejs / kit

web development, streamlined
https://kit.svelte.dev
MIT License
18.43k stars 1.89k forks source link

A way to reverse proxying (like Next.js middlewares) #10870

Open MarArMar opened 11 months ago

MarArMar commented 11 months ago

Describe the problem

I want to use PostHog, an open source analytics platform.

But request to their server from the browser can be blocked for CORS reasons or blocked by ad-blockers.

A reverse proxy would enable me to send its events through an endpoint in my own website.

https://posthog.com/docs/advanced/proxy/nextjs

I am blocked for this use case because Vercel, the host that I use, do not support middlewares for SvelteKit, see https://stackoverflow.com/questions/76937328/sveltekit-server-side-rewrites https://vercel.com/docs/frameworks/sveltekit#server-side-rendering "While server-side rendered SvelteKit apps do support middleware, SvelteKit does not support URL rewrites from middleware."

https://posthog.com/docs/advanced/proxy/vercel

I do not want to stop using vercel because they are very practical and Sentry, another lib that I use, does not support Cloudflare ATM.

I did not manage to make a tunneling endpoint because the posthog sdk sends streams of data, so If I read the stream and send the request I change the request from a stream to something else and their API endpoint seems to not support it

Describe the proposed solution

A middleware enabling rewrites like the one from Next.js

Alternatives considered

See problem description

Importance

would make my life easier

Additional Information

No response

hartwm commented 10 months ago

I am in same boat. I would like to be able to do something like https://github.com/vercel/examples/blob/main/edge-middleware/cookies/middleware.ts

taj-p commented 8 months ago

Hey! Could you do this work by using a server handle hook?

// hooks.server.ts

export const handle = (({ event, resolve }) => {
    // Proxy /ingest to PostHog
    if (event.url.pathname.startsWith('/ingest')) {
        // Set host to PostHog as per their [docs](https://posthog.com/docs/advanced/proxy)
        event.request.headers.set('host', 'app.posthog.com');
        // Let's not send our cookies to Posthog
        event.request.headers.delete('cookie');

        const path = event.url.pathname.replace('/ingest', '');
        const search = event.url.search;

        return fetch(`${PUBLIC_POSTHOG_API_PROXY_HOST}${path}${search}`, event.request);
    }

    return resolve(event);
}) satisfies Handle;

Where you create the posthog client via:

posthog.init(posthogConfig.apiKey, {
    api_host: "/ingest"
});
aubergene commented 8 months ago

I might be misunderstanding, but could Vite proxy work for this?

https://vitejs.dev/config/server-options.html#server-proxy

Edit: sorry yes am misunderstanding as this would only work in local dev