svelte-adapter-bun icon indicating copy to clipboard operation
svelte-adapter-bun copied to clipboard

fetch on server not including cookies (+page.server.ts)

Open Cluster2a opened this issue 2 years ago • 4 comments

Hey,

heaving the following code, the cookies on node are included.

const headers: HeadersInit = {
	contentType: 'application/json',
	Accept: 'application/json'
};

const response = await fetch(`${variables.API_URL}/dashboard`, {
	headers,
	credentials: 'include'
});

After switching to bun, the cookies are not included anymore. I tried to set the ORIGIN and add them manually via header, but for some reason no cookies at all reaches the backend (same tld).

Is there any way to work around this?

Cluster2a avatar Nov 23 '23 23:11 Cluster2a

Hey, do you use the fetch provided by the load function? If yes, you must manually inject the cookies in hooks.server.ts. For example:

export const handleFetch: HandleFetch = async ({event, request, fetch}) => {
    if (request.url.startsWith(PUBLIC_API_URL)) {
        request.headers.set("cookie", event.request.headers.get("cookie") ?? "");
    }

    return fetch(request);
}

I'm kinda surprised it has worked for you in node tbh, it didn't for me. At least not when using the provided fetch.

kyngs avatar Dec 17 '23 14:12 kyngs

@kyngs, sorry for the confusion, I am not talking about the hooks - there I needed the add the cookies manually - even on node.

I am talking about a fetch within a +page.server.ts ts (load()): image

Using the node adapter my cookies are passed to the backend, via credentials: 'include'.

Cluster2a avatar Dec 18 '23 08:12 Cluster2a

According to the sveltekit documentation the cookies should be passed from the client to the server fetch: https://kit.svelte.dev/docs/load#cookies

Cluster2a avatar Jan 17 '24 15:01 Cluster2a