Sveltekit Flash Message screenshot

Sveltekit Flash Message

Author Avatar Theme by Ciscoheat
Updated: 23 Jan 2025
317 Stars

Send temporary data after redirect, usually from endpoints. Works with both SSR and client.

Categories

Overview:

The SvelteKit Flash Message library is designed to pass temporary data to the next request in a SvelteKit application. It is particularly useful for displaying success or failure messages after a POST request, which should be shown on the redirected page rather than on the form itself. This functionality is commonly referred to as a “flash message” and is often seen in PHP apps. The library aims to make implementing flash messages in SvelteKit easier, encouraging well-behaved web apps that redirect after POST requests.

Features:

  • Passes temporary data to the next request
  • Displays success or failure messages after a POST request
  • Encourages redirects after POST requests

Installation:

  1. Add the flash message to app.d.ts (Typescript only): Add the type for the flash message to App.PageData in src/app.d.ts. The flash message can be a simple string or a more advanced data structure, as long as it is serializable.
  2. Wrap the load function of a top-level +layout or +page route: If you already have a top-level load function, import loadFlash and wrap your load function with it. If you’re not using any load functions, create a src/routes/+layout.server.ts file with the provided content.
  3. Display the flash message: Import getFlash in a layout or page component to display the flash message. getFlash will return a store that can be used to access the message.
  4. Send flash messages server-side: To send a flash message from the server, import redirect from sveltekit-flash-message/server and use it in load functions and form actions.

Summary:

The SvelteKit Flash Message library provides an easy way to implement flash messages in SvelteKit applications. It allows for the passing of temporary data to be displayed on the redirected page after a POST request. The library encourages well-behaved web apps that redirect after POST requests, making it easier to display success or failure messages to the user. The installation and usage guide provided in the documentation walks users through the necessary steps to integrate the library into their SvelteKit projects.