Sapper event for route change

So I placed this code to /src/routes/_layout.svelte:

  import AuthMiddleware from "../methods/authMiddleware.js";
  import { goto, stores } from '@sapper/app';
  const { page } = stores();

  if (typeof window !== "undefined" && typeof document !== "undefined") {
    page.subscribe(({ path, params, query }) => {
      const from = window.location.pathname;
      const redirect = (href) => { goto(href); }

      AuthMiddleware.beforeChange(from, path, redirect, params, query);
    })
  }

And this is authMiddleware.js file:

export default class AuthMiddleware {

  static beforeChange(from, to, redirect, params, query) {

    if (!AuthMiddleware._isUserAuthenticated()) {
      redirect("/login");
    }
  }

  // ~

  static _isUserAuthenticated() {
    return true; // TODO: Implement
  }
}

more information on route hooks can be found here

  • https://github.com/sveltejs/sapper/issues/30
  • https://sapper.svelte.dev/docs/#Stores