Search code examples
cookiessvelteserver-side-renderingsveltekit

+layout.svelte.ts and +page.server.ts are executed twice after a FETCH is done. No cookies are avalilable in those instances. With sveltekit why?


Using the default Sveltekit ("version": "2.5.4") demo application I have the following on the +page.server.ts:

import type { PageServerLoad } from './$types';
    
export const load: PageServerLoad = async ({locals, url, cookies}) => {
    console.log("MAIN SERVER PAGE LOAD --> +page.server.ts: -- COOKIE VALUE: ", cookies.get('DEBUG'));
    return {
      query: {}
    };
};

For the +layout.server.ts I have the following:

import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async ({ locals, cookies}) => {    
    console.log("LAYOUT SERVER LOAD --> +layout.server.ts -- ", cookies.get("DEBUG"));

    return {
      session: {}       
    };
};

I set a cookie on a different page for testing purposes:

export const load = (({ cookies }) => {
    cookies.set('DEBUG', "This is for debugging", { 
        secure: false, 
        httpOnly: false, 
        path: '/' 
    });
}) satisfies PageServerLoad;

On the main +page.svelte I have the following button:

async function query(){
    let access_token = "SSSLOJGGTFGHKLNOKJVUBI";
    const response = await fetch("http://localhost:8000/v1/apples/get-apple/", {
        method: 'GET',
        headers: {
            "Content-Type": "application/json", 
            "Authorization": `Bearer ${access_token}`,
            "Access-Control-Allow-Origin": "*"
        },
        body: null
    });
    console.log(await response.json());
}

I then do the following sequence: Reload the main page which triggers the following logs:

LAYOUT SERVER LOAD --> +layout.server.ts -- This is for debugging
MAIN SERVER PAGE LOAD --> +page.server.ts: -- COOKIE VALUE: This is for debugging

That is what I expect however after I then click the button that triggers the query function the following occurs:

LAYOUT SERVER LOAD --> +layout.server.ts -- This is for debugging
MAIN SERVER PAGE LOAD --> +page.server.ts: -- COOKIE VALUE: This is for debugging
LAYOUT SERVER LOAD --> +layout.server.ts -- undefined
MAIN SERVER PAGE LOAD --> +page.server.ts: -- COOKIE VALUE: undefined
LAYOUT SERVER LOAD --> +layout.server.ts -- undefined
MAIN SERVER PAGE LOAD --> +page.server.ts: -- COOKIE VALUE: undefined

As you can see the +layout.server and +page.server are triggered twice and there are also no cookies available. Why does this happen and how can I fix it?


Solution

  • I figured out that the cause of this issue is related to the VS-CODE extension "Console Ninja" - https://marketplace.visualstudio.com/items?itemName=WallabyJs.console-ninja.

    It seems to do some kind of load on its side that mirrors clicks. Not sure of the specifics but this was the cause.