routify icon indicating copy to clipboard operation
routify copied to clipboard

Error using $goto on Svelte 5

Open adg-mh opened this issue 1 year ago • 3 comments

Describe the bug

When trying to use $goto on a Svelte 5 project an error is thrown and navigation does not occur.

Reproduction

Reproduce by running starter project here and click the "Try to go" button.

Logs

Uncaught Svelte error: lifecycle_outside_component
`getContext(...)` can only be used during component initialisation

System Info

Binaries:
    Node: 23.6.0 - <redacted>\node-v23.6.0-win-x64\node.EXE
    npm: 10.9.2 - <redacted>\node-v23.6.0-win-x64\npm.CMD
  npmPackages:
    @roxi/routify: ^3.0.0-next.245 => 3.0.0-next.245
    svelte: ^5.0.0 => 5.16.0
    vite: ^6.0.0 => 6.0.5

adg-mh avatar Feb 12 '25 04:02 adg-mh

Seems to be an issue with Svelte 5 (sveltejs/svelte#14354):

In Svelte 5, the store's subscribe method is only called when the store is used, so if it's nested in a function, it's only called when the function is called. This obviously won't work with getContext.

agrear avatar Feb 12 '25 09:02 agrear

Svelte 5 no longer auto-subscribes to stores at component initialization. This isn’t listed as a breaking change, so I’m unsure if it’s intentional or a bug.

Since $goto relies on getContext() inside its subscription function (to resolve its parent component and relative paths), it won’t work unless explicitly triggered within a component.

A workaround is to manually initialize $goto at the root of your component:

import { goto } from '@roxi/routify'
$goto // manually initialize the helper

const redirect = () => $goto('/')

Since this behavior is due to Svelte’s internals, there’s nothing to fix on the Routify side, but happy to revisit if a solution emerges—closing for now.

jakobrosenberg avatar Feb 12 '25 10:02 jakobrosenberg

Thank you both for your quick replies. The workaround is working as expected.

adg-mh avatar Feb 12 '25 11:02 adg-mh