Sveltekit Flash is a little helper to display flash messages in your Sveltekit application.
You can find a demo here.
To install Sveltekit Flash, simply run:
pnpm install @maximux13/sveltekit-flash
src/hooks.server.(js|ts)
:import createFlashHandler from '@maximux13/sveltekit-flash';
/** @type {import('./$types.js').Handle} */
export const handle = createFlashHandler();
or if you already have a handle
function:
import { sequence } from '@sveltejs/kit';
import createFlashHandler from '@maximux13/sveltekit-flash';
/** @type {import('./$types.js').Handle} */
const handler = () => {
// your existing handler
}
export const handle = sequence(
createFlashHandler()
handler,
);
You can pass an options object to the createFlashHandler
function:
Option | Type | Default | Description |
---|---|---|---|
name | string | __flash |
The name of the session cookie. |
levels | string[] | ['success','info','warning','error','debug'] |
The levels of messages. Note: each value would be a added as a property of flash: eg: flash.success(message, tags) |
import { redirect } from '@sveltejs/kit';
/** @type {import('./$types.js').Actions} */
export const actions = {
default: async (event) => {
// your code here
// add a success message
event.locals.flash.success('Form submitted successfully');
// you can also add an info, warning, error or debug message
event.locals.flash.info('This is an info message');
// or add a custom level message
event.locals.flash('custom', 'Something went wrong');
throw redirect(302, '/message');
}
};
/** @type {import('./$types.js').PageServerLoad} */
export async function load(event) {
const messages = event.locals.messages;
return { messages };
}
<script>
/** @type {import('./$types.js').PageData} */
export let data;
const { messages } = data;
</script>
<ul>
{#each messages as message}
<li>{message.type}: {message.message}</li>
{/each}
</ul>
This project is licensed under the MIT License.