question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

$middleware.svelte to run code on client-side each time child page is rendered

See original GitHub issue

$ layout.svelte is a great idea to reflect the visual aspects and components common to all child pages.

It would be interesting if there was also a $ middleware.svelte with functions and routines that could be executed whenever a descendant page was called to be displayed, for example, because of access rules, filters, user functions or things like that, maybe more in terms of security.

I’m starting to work with sveltekit and I miss it.

I still haven’t found a way to do that in Sveltekit.

I would be grateful if someone clarified to me if it already exists or if there is a way to do it safely.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:2
  • Comments:21 (8 by maintainers)

github_iconTop GitHub Comments

6reactions
Rich-Harriscommented, Apr 22, 2021

load will re-run whenever its dependencies change. For example, this function…

export async function load({ session }) {
  if (!allowed(session.user)) {
    return { status: 403, error: new Error('Forbidden') };
  }

  // ...
}

…will re-run whenever session changes . That’s generally the place you want to do these sorts of checks.

Triggering a change to session without a page reload is up to the developer; for example you could do this sort of thing…

import { session } from '$app/stores';

async function logout() {
  await fetch('/auth/logout', { method: 'POST' });
  $session.user = null;  
}

…but that doesn’t solve the problem of e.g. logging out in a different tab. It’s solvable in userland, but I almost wonder if SvelteKit should have some built-in stuff for refreshing the session from the server periodically (including when you refocus a page, swr style). #46 included some thinking along those lines.

4reactions
tarkahcommented, Apr 29, 2021

@moisesbites You can get load to run everytime, even within a $layout page for all sub-pages, by adding the following to your load function:

// Workaround to get this function to trigger on every router change
if (page.path) {}

I’m doing the same thing where I verify the JWT everytime the user changes routes under the /private route in my app. Here is my full load function:

<script lang="ts" context="module">
	import type { Load } from '@sveltejs/kit';

	export const load: Load = async ({ page, fetch, session }) => {
		const resp = await fetch('/api/auth/verify');

		// Workaround to get this function to trigger on every router change
		if (page.path) {
			//
		}

		if (resp.status === 200) {
			return {};
		}

		session.authenticated = false;

		return {
			status: 303,
			redirect: '/login'
		};
	};
</script>

I think this has something to do with the fact that load now depends on page, which changes every time the router changes, so it causes it to trigger. But I’m not exactly sure what’s going on under the hood.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Modules • Docs • SvelteKit
A subdirectory of $lib . SvelteKit will prevent you from importing any modules in $lib/server into client-side code. See server-only modules. $service ...
Read more >
'Sapper: Towards the ideal web app framework' - Svelte
Finding the code responsible for a given page is easy, because you can just look at the filesystem rather than playing 'guess the...
Read more >
Page options • Docs • SvelteKit
By default, SvelteKit will render (or prerender) any component first on the server and send it to the client as HTML. It will...
Read more >
Docs • Sapper
Each page of your app is a Svelte component; You create pages by adding files to the src/routes directory of your project. These...
Read more >
FAQ • SvelteKit
You can execute any one-time setup code in hooks.js and import your database helpers into any endpoint that needs them. How do I...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found