Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend Locals interface in SvelteKit

The Svelte documentation shows how to set an element on locals in hooks: https://kit.svelte.dev/docs/hooks#server-hooks

event.locals.user = await getUserInformation(event.cookies.get('sessionid'));

If I try to extend the locals Object in TypeScript I get an error, of not existing property.

Property 'user' does not exist on type 'Locals'

The App.Locals interface is empty so it should be a normal error message of the system. How could I extend the App.Locals interface of Svelte with attributes like user or session and have this information also available in my server routes? I want to avoid to cast or define it everywhere by my self.

like image 872
CordlessWool Avatar asked Sep 12 '25 15:09

CordlessWool


1 Answers

There should already be a app.d.ts which declares the interface in a new SvelteKit project. If you do not have such a file, you can just create your own declarations.

The interface is namespaced (see App):

declare namespace App {
    interface Locals {
        user: UserInfo; // Your type here
    }

    interface PageData {}

    interface Platform {}
}

(If you have any imports, you need declare global { namespace App { ... } } instead, otherwise the namespace will be scoped to what now is a module.)

like image 58
H.B. Avatar answered Sep 15 '25 05:09

H.B.