Search code examples
sveltesveltekit

How to pass data from page endpoints to a layout component in Sveltekit?


A page endpoint is a convenient way to handle requests in Sveltekit, which also makes it a useful place to handle the errors that can occur, as in:

src/routes/items.js

export async function POST({ request }) {
  const [errors, item] = await db.create(request)
 
  if (errors) {
    return {
      status: 400,
      body: { errors }
    }
  }
}

Displaying the error might not be made in src/routes/items.svelte however. Often you want them to be shown on the top of the page, or as a toast notification. The place for these would be in a layout component:

src/routes/__layout.svelte

<header>
  <Errors />
</header>

<main>
  <slot></slot>
</main>

It's quite boilerplatey to have code in every route component that checks for errors and passes them on to another component, so is there a more svelte way to do this? The load function is being changed for 1.0, and I'd really like to keep it simple with everything done in a page endpoint.


Solution

  • I have solved this by using a cookie that gets passed on to locals and then session for display in any component.

    It was a bit harder than expected, especially to make it work both with SSR and on the client, so I have packaged up the solution in a library here: https://www.npmjs.com/package/sveltekit-flash-message