How to extend Locals interface in svletekit

Viewed 25

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 sytem. 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.

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 {}
}
Related