Sveletkit Redirect doesn't seem to work for me

Viewed 1355

I keep having an issue with returning a redirect from the load method in sveltekit. I'm ready to quit. So this simple little redirect doesn't see to work for me in __layout.svelte

export async function load() {

    let user = false

    if (!user) {
      return {
          status: 301,
          redirect: '/login'
        }
    } else {
      return {}
    }

  }

And I get the screenshot below. Nothing I do seems to work with redirects. Any suggestions as to why I can't seem to get this simple thing to work.

enter image description here

1 Answers

Solved the problem. Because it's __layout.svelte the code needed a check for the url.pathname otherwise it seems to act like a loop.

The solution:

export async function load({ url }) {

    let user = false

    if (!user && !url.pathname.includes('/login')) {
      return {
          status: 301,
          redirect: '/login'
        }
    } else if (user && url.pathname.includes('/login')){
      return {
          status: 301,
          redirect: '/'
        }
    } else {
      return {}
    }

  }
Related