sveltekit-flash-message

repository·master·Indexed 43 days ago

https://github.com/ciscoheat/sveltekit-flash-message

A SvelteKit library for sending temporary, serializable data (flash messages) to the next request. It supports both SSR and client-side usage, following the 'Redirect after Post' pattern to display success or error notifications after form actions or redirects. Version 2.4.6 includes features like automatic navigation clearing, time-based clearing via clearAfterMs, and support for Svelte 4 and 5.

Tokens
5.4K
Snippets
22
Records
25
Agent score
54%

What's inside sveltekit-flash-message

  1. Update flash messages after client-side fetch

    master

    When using the browser fetch API instead of SvelteKit's built-in form handling, the flash message store will not update automatically. You must call updateFlash(page) after the fetch completes to sync the state.

    <script lang="ts">
      import { updateFlash } from 'sveltekit-flash-message';
      import { page } from '$app/state';
    
      async function submitForm(e: Event) {
        const form = e.target as HTMLFormElement;
        const body = new FormData(form);
    
        await fetch(form.action, { method: 'POST', body });
        await updateFlash(page);
      }
    </script>
    
    <form method="POST" action="/test" on:submit|preventDefault={submitForm}>
      <button>Submit with fetch</button>
    </form>
  2. Wrap the top-level load function with loadFlash

    master

    To enable flash messages, you must wrap your top-level load function in src/routes/+layout.server.ts.

    If you don't have a load function, simply export the library's load: export { load } from 'sveltekit-flash-message/server';.

    If you already have a load function, wrap it using loadFlash:

    Note: Do not call load or loadFlash in any child routes, as the flash cookie is deleted immediately upon its first discovery in the top-level load function.

    // src/routes/+layout.server.ts
    import { loadFlash } from 'sveltekit-flash-message/server';
    
    export const load = loadFlash(async (event) => {
      const data = { someOther: 'data' };
      return data;
    });
  3. Configure TypeScript types for flash messages

    master

    In src/app.d.ts, add the flash property to the App.PageData interface. The flash message must be a serializable, JSON-friendly data structure. You can use a simple string or a more complex object like { type: 'success' | 'error'; message: string }.

    // src/app.d.ts
    declare global {
      namespace App {
        interface PageData {
          flash?: { type: 'success' | 'error'; message: string };
        }
      }
    }
    
    export {};
  4. Migrate from sveltekit-flash-message 1.x to 2.x

    master

    If you are upgrading from version 1.x to 2.x, you must apply the following breaking changes:

    1. Rename Functions

    • Replace loadFlashMessage with loadFlash.
    • initFlash is now primarily used for configuration; you can use getFlash directly in most scenarios.

    2. Automatic Navigation Clearing

    • The manual beforeNavigate snippet used to clear flash messages after navigation is no longer required. Clearing is now automatic.
    • To prevent automatic clearing on navigation, set the clearOnNavigate option to false.

    3. Time-based Clearing

    • If you previously used a custom snippet to clear messages after a specific duration, remove it and use the clearAfterMs option instead.
  5. Manage flash message routing with FlashRouter

    master

    The FlashRouter class is responsible for managing the mapping between route IDs and FlashMessage instances. It allows you to associate specific flash messages with specific URL paths or patterns.

    Key behaviors:

    • Default Route: If no specific route matches, the router falls back to a default route (identified by an empty string '').
    • Route Matching: When retrieving a message for a routeId, the router attempts to find an exact match. If no exact match exists, it uses getClosestRoute to find the longest matching prefix among registered routes.
    • Lifecycle Management: The router automatically clears any active flash message timeouts when it is destroyed.
  6. Implement toast notifications using flash messages

    master

    To treat flash messages as transient events (like toasts) rather than static page content, use an $effect to trigger a toast library and then clear the flash store.

    <script>
      import { getFlash } from 'sveltekit-flash-message';
      import { page } from '$app/state';
      import toast from 'svelte-french-toast';
    
      const flash = getFlash(page);
    
      $effect(() => {
        if (!$flash) return;
    
        toast($flash.message, {
          icon: $flash.type == 'success' ? '✅' : '❌'
        });
    
        // Clear the flash message to avoid double-toasting.
        $flash = undefined;
      });
    </script>
  7. Send flash messages from the server

    master

    You can send flash messages from server-side load functions, form actions, or endpoints using redirect or setFlash from sveltekit-flash-message/server.

    import { redirect } from 'sveltekit-flash-message/server';
    
    // Redirect with a specific location and message (303 redirect)
    redirect('/', { type: 'success', message: 'Success!' }, cookies);
    
    // Redirect with a specific status and location
    redirect(302, '/login', { type: 'error', message: 'Session expired' }, cookies);
  8. Configure flash message behavior with getFlash and initFlash

    master

    You can customize how flash messages behave using options passed to getFlash or initFlash.

    Options:

    • clearOnNavigate (boolean): If true (default), the message is removed when navigating to a different route.
    • clearAfterMs (number): Time in milliseconds before the message is automatically set to undefined.
    • clearArray (boolean): If your flash data is an array, setting this to true ensures previous messages are cleared instead of concatenated.
    • flashCookieOptions (CookieSerializeOptions): Customizes the underlying cookie settings (e.g., sameSite, maxAge).
    import { getFlash, initFlash } from 'sveltekit-flash-message';
    import { page } from '$app/state';
    
    // Use in a component
    const flash = getFlash(page, {
      clearAfterMs: 5000,
      clearOnNavigate: true
    });
    
    // Or initialize globally in a layout
    initFlash(page, {
      flashCookieOptions: { sameSite: 'lax' }
    });
  9. Display flash messages in Svelte components

    master

    Use getFlash(page) to obtain a Svelte store containing the current flash message. You can then use the $ prefix to access the message in your markup or logic.

    <script lang="ts">
      import { getFlash } from 'sveltekit-flash-message';
      import { page } from '$app/state';
    
      const flash = getFlash(page);
    </script>
    
    {#if $flash}
      <div class="flash">{$flash.message}</div>
    {/if}
  10. Set flash messages without redirecting

    master

    To display a flash message (e.g., for validation errors) without performing a redirect, use setFlash from sveltekit-flash-message/server inside a form action.

    import { fail } from '@sveltejs/kit';
    import { setFlash } from 'sveltekit-flash-message/server';
    
    export const actions = {
      default: async ({ request, cookies }) => {
        const form = await request.formData();
        if (!form.get('text')) {
          setFlash({ type: 'error', message: 'Please enter text.' }, cookies);
          return fail(400);
        }
      }
    };
  11. Configure FlashOptions for sveltekit-flash-message

    master

    When initializing or extending the flash message functionality, you can provide a FlashOptions object to control how messages are cleared and how the underlying cookie is configured.

    Available Options

    OptionTypeDefaultDescription
    clearArraybooleanfalseWhether to clear the entire array of messages.
    clearOnNavigatebooleantrueWhether to clear messages when the user navigates.
    clearAfterMsnumber0Time in milliseconds after which messages should be cleared.
    flashCookieOptionsCookieSerializeOptions{ path: '/', maxAge: 120, httpOnly: false, sameSite: 'strict' }Configuration for the cookie used to store flash messages.

    The flashCookieOptions object accepts standard CookieSerializeOptions. The default settings are:

    • path: '/'
    • maxAge: 120 (seconds)
    • httpOnly: false
    • sameSite: 'strict'
    const myOptions: FlashOptions = {
      clearOnNavigate: false,
      flashCookieOptions: {
        maxAge: 3600,
        httpOnly: true
      }
    };