ciscoheat / sveltekit-flash-message

Send temporary data after redirect, usually from endpoints. Works with both SSR and client.
https://www.npmjs.com/package/sveltekit-flash-message
MIT License
246 stars 5 forks source link

flash store undefined after redirect #28

Closed MikaelJohnAndersson closed 9 months ago

MikaelJohnAndersson commented 9 months ago

Sorry if I'm missing something obvious, I'm having issues trying to retrieve flash messages after a redirect in a form action. I'm also using layout groups and found #23. Seems similar but might be unrelated.

Top level layout with a conditional redirect if no user exist:

// src/routes/(app)/+layout.server.ts

import type { LayoutServerLoad } from './$types';
import { loadFlash, redirect } from 'sveltekit-flash-message/server';

export const load: LayoutServerLoad = loadFlash(({ locals: { user } }) => {
    if (!user) {
        throw redirect(302, '/login');
    }
});

Route where I want to redirect with a flash message on success:

// src/routes/(app)/shop/categories/[slug]/+page.server.ts

import { redirect } from 'sveltekit-flash-message/server';

export const actions = {
    default: async (event) => {
                ... 

                // Using new slug after successful edit
                // I also tried including explicit status code in signature
        throw redirect(
            `/shop/categories/${newSlug}`,
            { type: 'success', message: 'Edit success' },
            event
        );
    }
};
// src/routes/(app)/shop/categories/[slug]/+page.svelte

<script lang="ts">
    import { getFlash } from 'sveltekit-flash-message';
    import { page } from '$app/stores';

    export let data;

    const flash = getFlash(page);
    $: console.log($flash);
</script>

The redirect works fine, but $flash is always undefined. If the edit results in an error, I'm also trying setFlash and returning fail() as the docs suggests, with same results ($flash is undefined).

I'm using version 2.2.1, and I should also mention I'm using superforms, if that might be relevant.

MikaelJohnAndersson commented 9 months ago

So it seems it was a user error, not entirely unexpected :) Turns out I set my auth cookie on the response headers in hooks.server.ts using Headers.set(), effectively overwriting the flash cookie.

Solution was to use Headers.append(), preserving the flash cookie in the response. Closing this as completed.