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