Skip to content

Allow $effect.pre to run on the serverΒ #9278

@Thiagolino8

Description

@Thiagolino8

Describe the problem

A common practice when using SvelteKit is to use reactive expressions for expressions that need to be executed reactively on the client but also need to be executed non-reactively on the server during ssr
Svelte 5 will bring the $effect and $effect.pre runes to replace reactive expressions, but with the difference that these runes will not be executed on the server, creating the need to repeat code to achieve the same behavior

// before
$: {
    // really big expression
}
// after
import {browser} from '$app/environment'

if(!browser) {
    // really big expression
}

$effect(() => {
    // really big expression again
})

Describe the proposed solution

The reason the $effect rune does not run on the server is because it runs after the DOM is mounted, but the $effect.pre rune does not need to wait for the DOM, and is therefore ideal for reproducing the behavior of reactive expressions
Just as the $state and $derived runes are transformed into common variables during SSR, the $effect.pre rune can be transformed into a simple IIFE

Alternatives considered

Manually transform the expression into a function, but this requires changing the code design and still requires duplicate execution with environment checking

Importance

would make my life easier

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions